通过匹配字典的值,在列表中查找字典的索引 [英] Find the index of a dict within a list, by matching the dict's value

查看:83
本文介绍了通过匹配字典的值,在列表中查找字典的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典列表:

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

如何通过匹配 name = 'Tom' 来有效地找到索引位置 [0]、[1] 或 [2]?

How can I efficiently find the index position [0],[1], or [2] by matching on name = 'Tom'?

如果这是一个一维列表,我可以执行 list.index() 但我不确定如何通过搜索列表中的字典的值来继续.

If this were a one-dimensional list I could do list.index() but I'm not sure how to proceed by searching the values of the dicts within the list.

推荐答案

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

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

如果您需要从名称中重复获取,您应该按名称索引它们(使用字典),这样 get 操作将是 O(1) 时间.一个想法:

If you need to fetch repeatedly from name, you should index them by name (using a dictionary), this way get operations would be O(1) time. An idea:

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

info_by_name = build_dict(lst, key="name")
tom_info = info_by_name.get("Tom")
# {'index': 1, 'id': '2345', 'name': 'Tom'}

这篇关于通过匹配字典的值,在列表中查找字典的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆