如何在python字典列表中找到一个值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17149561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find a value in a list of python dictionaries?
提问by bobsr
Have a list of python dictionaries in the following format. How would you do a search to find a specific name exists?
有以下格式的python字典列表。您将如何进行搜索以查找存在的特定名称?
label = [{'date': datetime.datetime(2013, 6, 17, 8, 56, 24, 2347),
'name': 'Test',
'pos': 6},
{'date': datetime.datetime(2013, 6, 17, 8, 56, 24, 2347),
'name': 'Name 2',
'pos': 1}]
The following did not work:
以下方法无效:
if 'Test' in label[name]
'Test' in label.values()
采纳答案by Martijn Pieters
You'd have to search through all dictionaries in your list; use any()with a generator expression:
您必须搜索列表中的所有词典;使用any()与发电机表达式:
any(d['name'] == 'Test' for d in label)
This will short circuit; return Truewhen the firstmatch is found, or return Falseif none of the dictionaries match.
这会短路;返回True时,第一个找到匹配,或者返回False如果没有字典的匹配。
回答by Eric
You might also be after:
您可能还在追求:
>>> match = next((l for l in label if l['name'] == 'Test'), None)
>>> print match
{'date': datetime.datetime(2013, 6, 17, 8, 56, 24, 2347),
'name': 'Test',
'pos': 6}
Or possibly more clearly:
或者可能更清楚:
match = None
for l in label:
if l['name'] == 'Test':
match = l
break

