others - 通过匹配字典的值在列表中查找dict的索引

我有一个字典列表:


list = [{'id':'1234','name':'Jason'},
 {'id':'2345','name':'Tom'},
 {'id':'3456','name':'Art'}]

如何通过匹配名称查找索引位置[0] ,[1]或[2]?

时间:


 next(index for (index, d) in enumerate(lst) if d["name"] =="Tom")
# 1

只是个想法:


def build_dict(seq, key):
 return dict((d[key], dict(d, index=i)) for (i, d) in enumerate(seq))

d = build_dict(lst, key="name")
d["Tom"] 
# {'index': 1, 'id': '2345', 'name': 'Tom'}

简单的可读版本是


def find(lst, key, value):
 for i, dic in enumerate(lst):
 if dic[key] == value:
 return i
 return -1

这里有一个方法,


>>> L = [{'id':'1234','name':'Jason'},
... {'id':'2345','name':'Tom'},
... {'id':'3456','name':'Art'}]
>>> [i for i,_ in enumerate(L) if _['name'] == 'Tom'][0]
1

下面是字典位置的索引,如果它存在的话。


dicts = [{'id':'1234','name':'Jason'},
 {'id':'2345','name':'Tom'},
 {'id':'3456','name':'Art'}]

def find_index(dicts, key, value):
 class Null: pass
 for i, d in enumerate(dicts):
 if d.get(key, Null) == value:
 return i
 else:
 raise ValueError('no dict with the key and value combination found')

print find_index(dicts, 'name', 'Tom')
# 1
find_index(dicts, 'name', 'Ensnare')
# ValueError: no dict with the key and value combination found

使用筛选器/索引组合似乎最合理

names= [{},{'name':'汤姆'},{'姓名':'托尼'}] names= 0 names= 1 names=2,名称) 1 names= 3)

如果你认为有多个匹配的[nanes.index(n) for item in filter(lambda n: n.get('name') =='Tom', names)] [1 ]

...