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?
The keys() function and the "in" operator can be used to see if a key exists in a dictionary. The keys() method returns a list of keys in the dictionary, and the "if, in" statement checks whether the provided key is in the list. It returns True if the key exists; otherwise, it returns False.
Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable.
You can use any.
if any('silver' in d for d in a['values']):
# do stuff
# 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
filter()
next()
any()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With