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