将多个列表映射到字典
问题描述:
我有5个列表,我想将它们映射到分层字典。
I have 5 lists and I want to map them to a hierarchical dictionary.
让我们说:
temp = [25, 25, 25, 25]
volt = [3.8,3.8,3.8,3.8]
chan = [1,1,6,6]
rate = [12,14,12,14]
power = [13.2,15.3,13.8,15.1]
和我想要的字典是这样的:
and what I want as my dictionary is this:
{25:{3.8:{1:{12:13.2,14:15.3},6:{12:13.8,14:15.1}}}}
基本上字典结构是:
{temp:{volt:{chan:{rate:power}}}}
我尝试使用zip功能,但在这种情况下没有帮助,因为在顶级列表中重复的值
I tried using the zip function but it does not help in this case because of the repeated values in the list at the top level
答
这只是稍微测试一下,但它似乎是诀窍。基本上, f
是,创建一个 defaultdict
defaultdicts
。
This is only slightly tested, but it seems to do the trick. Basically, what f
does, is to create a defaultdict
of defaultdicts
.
f = lambda: collections.defaultdict(f)
d = f()
for i in range(len(temp)):
d[temp[i]][volt[i]][chan[i]][rate[i]] = power[i]
示例:
>>> print d[25][3.8][6][14]
15.1
想法来自相关问题的答案。)