6

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?

martineau
  • 112,593
  • 23
  • 157
  • 280
Kev
  • 477
  • 1
  • 7
  • 25
  • Are you sure you got that error from that exact code? Please share the entire error message. – AMC Jan 12 '20 at 04:33
  • Does this answer your question? [How can I check if key exists in list of dicts in python?](https://stackoverflow.com/questions/14790980/how-can-i-check-if-key-exists-in-list-of-dicts-in-python) – Georgy Jan 12 '20 at 15:51

4 Answers4

10

You can use any.

if any('silver' in d for d in a['values']):
   # do stuff
abc
  • 10,886
  • 2
  • 22
  • 46
4
# 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
Felipe
  • 6,255
  • 2
  • 26
  • 34
3

You can try this:

if 'silver' in a['values'][0].keys():
Giannis Clipper
  • 682
  • 4
  • 9
0

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.

JHS
  • 1,377
  • 16
  • 28