[英]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.