繁体   English   中英

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

[英]How to check if in list in dictionary is a key?

我有一本这样的字典:

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

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

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

但我收到错误:

NameError: name 'silver' is not defined

那么我怎样才能在 python 中实现呢?

您可以使用任何.

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

你可以试试这个:

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

如果您想采用列表插值方法,您可以将 dicts 列表展平为一个键列表,如下所示:

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

基于这个对列表列表进行扁平化的答案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM