如何检查字典中的列表是否为键?

时间:2020-01-11 19:16:28

标签: python list dictionary

我有这样的字典:

a = {'values': [{'silver': '10'}, {'gold': '50'}]}

现在,我想检查键“ silver”是否在字典中:

if 'silver' in a['values']:

但是我收到错误消息:

NameError: name 'silver' is not defined

那么我如何在python中实现呢?

4 个答案:

答案 0 :(得分:10)

您可以使用any

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

答案 1 :(得分: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

答案 2 :(得分:3)

您可以尝试以下方法:

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

答案 3 :(得分:0)

如果要采用列表插值方法,可以将字典列表展平为键列表,如下所示:

In: [key for pair in a['values'] for key in pair.keys()]
Out: ['silver', 'gold']

然后:

In: 'silver' in [key for pair in a['values'] for key in pair.keys()]
Out: True

基于this answer展平列表列表。

相关问题