![](/img/trans.png)
[英]How to create a nested dictionary from existing dictionary with set and list of tuples
[英]Fast way to create a nested dictionary from a list of tuples without a for loop
我知道以前有人問過類似的問題,但我找不到適合我的情況的答案。
假設我有以下元組列表:
d = [('first', 1), ('second', 2), ('third', 3)]
我可以很容易地將它轉換成字典:
dict(d)
# {'first': 1, 'second': 2, 'third': 3}
現在,如果我有以下元組列表:
d = [('a', 'first', 1), ('a', 'second', 2), ('b', 'third', 3)]
我怎樣才能最有效地獲得以下嵌套字典:
{'a': {'first': 1, 'second': 2}, 'b': {'third': 3}}
這是我現在的解決方案:
from collections import defaultdict
dd = defaultdict(dict)
for a, b, c in d:
dd[a][b] = c
# defaultdict(dict, {'a': {'first': 1, 'second': 2}, 'b': {'third': 3}})
這是執行此操作的最有效方法嗎? 是否可以避免 for 循環? 很可能我必須處理d
非常大的情況,並且這種方法可能無法很好地擴展。 這部分對於我正在構建的 web 應用程序至關重要,這就是性能非常重要的原因。
輸入/反饋/幫助表示贊賞!
你可以用groupby
做
from itertools import groupby
result = {k:dict([(i[1],i[2]) for i in l]) for k, l in groupby(d, key=lambda x: x[0])}
# Result
{'a': {'first': 1, 'second': 2}, 'b': {'third': 3}}
當您使用groupby
時,值應該按鍵排序。
編輯:
您可以使用map
避免第二次循環。
{k:dict(map(lambda x: (x[1],x[2]), l)) for k, l in groupby(d, key=lambda x: x[0])}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.