How to search a list with nested dictionary by dictionary value, returning the index of the list with the dictionary element

jen*_*nla 3 python dictionary list

If I have a list with some nested dictionaries each containing the same keyset and value type set.

list = [{'a': 1, 'b': 2.0, 'c': 3.0}, 
        {'a': 4, 'b': 5.0, 'c': 6.0}, 
        {'a': 7, 'b': 8.0, 'c': 9.0}]
Run Code Online (Sandbox Code Playgroud)

返回 '​​b' 字典键中 5.0 第一次出现的列表索引的最 Pythonic 方法是什么,如果没有找到,则返回 None ?

我知道我可以手动迭代和搜索:

#with the list above...

result = None
for dict in list:
  if dict['b'] == 5.0:
    result = list.index(dict)
    break
print result
#(prints 1)


#as another example, same code but searching for a different value in 'b'
result = None
for dict in list:
  if dict['b'] == 6.0:
    result = list.index(dict)
    break
print result
#(prints None)
Run Code Online (Sandbox Code Playgroud)

但这似乎相当麻烦。先感谢您。

And*_*ely 8

您可以使用next()内置方法(None如果没有找到,这将返回):

lst = [{'a': 1, 'b': 2.0, 'c': 3.0},
       {'a': 4, 'b': 5.0, 'c': 6.0},
       {'a': 7, 'b': 8.0, 'c': 9.0}]

print(next((i for i, d in enumerate(lst) if d['b'] == 5.0), None))
Run Code Online (Sandbox Code Playgroud)

印刷:

1
Run Code Online (Sandbox Code Playgroud)