[英]What's the most efficient way to access sibling dictionary value in a Python dict?
在Python中,我有一个字典列表,如下所示:
matchings = [
{'id': 'someid1', 'domain': 'somedomain1.com'},
{'id': 'someid2', 'domain': 'somedomain2.com'},
{'id': 'someid3', 'domain': 'somedomain3.com'}
]
而且,我有一个变量:
the_id = 'someid3'
检索项目域值的最有效方法是什么?
您可以使用列表理解 :
domains = [matching['domain'] for matching in matchings if matching['id'] == the_id]
其格式符合以下格式:
resulting_list = [item_to_return for item in items if condition]
并且基本上封装了以下所有功能:
domains = []
for matching in matchings:
if matching['id'] == the_id:
domains.append(matching['domain'])
使用列表推导将所有功能表示在一行中。
我重组了matchings
。
from collections import defaultdict
matchings_ix= defaultdict(list)
for m in matchings:
matchings_ix[m['id']].append( m )
现在最有效的查找是
matchings_ix[ d ]
我能想到的最好的是做一个明确的搜索。 这是我对Python感到失望的一个领域,它不会像C ++ STL算法那样为您提供一组强大的解耦构建块
[d["domain"] for d in matchings if d["id"] == "someid3"]
列表中有字典的事实并不重要 - 问题减少到在列表中查找某些属性为真的项目。 为此,@ Soviut的答案的一些变化是要走的路:循环或列表理解,检查每个项目,直到找到匹配。 这些物品没有固有的顺序,所以你甚至不能依赖像bisect那样有用的东西。
我真的很喜欢在这种情况下使用过滤器 。 它接受一个函数和一个iterable,并返回函数返回True的元素列表(在Python 3.x中它返回一个迭代器)。
>>> filter(lambda x: x['id'] == 'someid3', matchings)
<<< [{'domain': 'somedomain3.com', 'id': 'someid3'}]
您可以使用列表解析来获取所有域的列表:
>>> [x['domain'] for x in filter(lambda x: x['id'] == 'someid3', matchings)]
<<< ['somedomain3.com']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.