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