2

I have a Python dict like this:

{
    'TagList': [
        {
            'Key': 'tag1',
            'Value': 'val'
        },
        {
            'Key': 'tag2',
            'Value': 'val'
        },
        {
            'Key': 'tag3',
            'Value': 'val'
        },
        ...
    ]
}

How do I loop through this dict to search if the Key tag1 is available.

EDIT: @Willem Van Onsem's solution works great. But I forgot to mention that I need to check more than 1 Key, so for example:

If Tag1 and Tag2 exist => true
If either Tag1 or Tag2 is missing` => false
2
  • do you have more keys than 'TagList' in your dict? Commented Jul 14, 2017 at 17:45
  • No only 1 key like TagList Commented Jul 14, 2017 at 17:47

4 Answers 4

5

Assuming that your dictionary contains a key 'TagList' and you are only interested in the dictionaries in the list associated with that key, you can use:

any(subd.get('Key') == 'tag1' for subd in the_dict['TagList'])

Where the dictionary the_dict is the one you want to inspect.

We thus use the any(..) builtin with a generator expression that iterates through the list associated with the 'TagList' key. For each such subdictionary, we check if the key 'Key' is associated with the value 'tag1'. In case no key 'Key' is present in one or more of the subdictionaries, that is not a problem since we use .get(..).

For your given dictionary, this generates:

>>> any(subd.get('Key') == 'tag1' for subd in the_dict['TagList'])
True

Multiple values

If you want to check that all values of a list occur in the subdictionaries, we can use the following two-liner (given the "tag names" are hashable, strings are hashable):

tag_names = {subd.get('Key') for subd in the_dict['TagList']}
all(tag in tag_names for tag in ('tag1','tag2'))

Here the all(..) will return True if all the tag names in the tuple at the right (('tag1','tag2')) are each in at least one subdictionary.

For example:

>>> all(tag in tag_names for tag in ('tag1','tag2'))
True
>>> all(tag in tag_names for tag in ('tag1','tag2','tag3'))
True
>>> all(tag in tag_names for tag in ('tag1','tag2','tag4'))
False
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, this 1-line solution works great. Can I add another condition to this code to check if both tag1 "and" tag2 are there?
@Casper: that's a harder problem. But it is possible. I will edit the answer.
Wow many thanks, I never knew about these elegant functions of Python, now I can get rid of those for loops...
@WillemVanOnsem hi Willem, I stumbled upon this new format and the current answer doesn't seem to apply. { 'Tags': { 'Key': 'Value' } } I want to check if the value 'Key' matches my search key
@Casper: please edit your question, or ask a new one.
2

You can use the following loop:

for key in d:
    for item in d[key]:
        for deep_key in item:
            if item[deep_key] == 'tag1': # whatever you are looking for
                print('Found')

Comments

0
from collections import ChainMap

'tag1' in ChainMap(*d['TagList'])

or if you want the tag1's value

ChainMap(*d['TagList'])['tag1']

Comments

0

If you declare your dictionary as a_dict then their is the other way to find the Key tag1. If found then it will return the True else False.

tag_list = a_dict['TagList']
result = next((True for item in tag_list if item["Key"] == "tag1"),False)
print(result)

for multiple :

a,b=next((True for item in tag_list if item["Key"] == "ta1"),False),\
    next((True for item in tag_list if item["Key"] == "tag2"), False)
result = a and b
print(result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.