简体   繁体   English

如何在python词典列表中查找值?

[英]How to find a value in a list of python dictionaries?

Have a list of python dictionaries in the following format. 以下列格式列出python词典。 How would you do a search to find a specific name exists? 您如何进行搜索才能找到特定名称?

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()

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 True when the first match is found, or return False if none of the dictionaries match. 找到第一个匹配项时返回True ,如果没有任何字典匹配则返回False

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

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

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