Reputation: 577
I have a dictionary like this:
a = {'values': [{'silver': '10'}, {'gold': '50'}]}
Now I would like to check if the key 'silver' is in the dictionary:
if 'silver' in a['values']:
But I receive the error:
NameError: name 'silver' is not defined
So how can I achieve that in python?
Upvotes: 6
Views: 270
Reputation: 1428
If you want to take a list interpolation approach, you can flatten the list of dicts into a list of keys like so:
In: [key for pair in a['values'] for key in pair.keys()]
Out: ['silver', 'gold']
Then:
In: 'silver' in [key for pair in a['values'] for key in pair.keys()]
Out: True
Based on this answer to flattening a list of lists.
Upvotes: 0
Reputation: 8025
# Notice that a['values'] is a list of dictionaries.
>>> a = {'values': [{'silver': '10'}, {'gold': '50'}]}
# Therefore, it makes sense that 'silver' is not inside a['values'].
>>> 'silver' in a['values']
False
# What is inside is {'silver': '10'}.
>>> a['values']
[{'silver': '10'}, {'gold': '50'}]
# To find the matching key, you could use the filter function.
>>> matches = filter(lambda x: 'silver' in x.keys(), a['values'])
# 'next' allows you to view the matches the filter found.
>>> next(matches)
{'silver': '10'}
# 'any' allows you to check if there is any matches given the filter.
>>> any(matches):
True
Upvotes: 4