Kev
Kev

Reputation: 577

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?

Upvotes: 6

Views: 270

Answers (4)

JHS
JHS

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

felipe
felipe

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

Giannis Clipper
Giannis Clipper

Reputation: 707

You can try this:

if 'silver' in a['values'][0].keys():

Upvotes: 3

abc
abc

Reputation: 11929

You can use any.

if any('silver' in d for d in a['values']):
   # do stuff

Upvotes: 10

Related Questions