Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if in list in dictionary is a key?

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?

like image 508
Kev Avatar asked Jan 11 '20 19:01

Kev


People also ask

How do you check if a key value exists in a list of dictionary 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.

Can a list be a dictionary key?

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.


2 Answers

You can use any.

if any('silver' in d for d in a['values']):
   # do stuff
like image 91
abc Avatar answered Sep 20 '22 17:09

abc


# 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()
like image 42
Felipe Avatar answered Sep 19 '22 17:09

Felipe