简体   繁体   English

将多个列表映射到字典

[英]mapping multiple lists to dictionary

I have 5 lists and I want to map them to a hierarchical dictionary. 我有5个列表,我想将它们映射到分层词典。

let's say i have: 假设我有:

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}}}}

Basically the dictionary structure is: 字典结构基本上是:

{temp:{volt:{chan:{rate:power}}}}

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 我尝试使用zip函数,但在这种情况下它无济于事,因为顶层列表中的重复值

This is only slightly tested, but it seems to do the trick. 这只是稍作测试,但似乎可以解决问题。 Basically, what f does, is to create a defaultdict of defaultdicts . 基本上, f作用是创建defaultdictdefaultdicts

f = lambda: collections.defaultdict(f)
d = f()
for i in range(len(temp)):
    d[temp[i]][volt[i]][chan[i]][rate[i]] = power[i]

Example: 例:

>>> print d[25][3.8][6][14]
15.1

(The idea is borrowed from this answer to a related question .) (这个想法是从相关问题的答案中借来的。)

You can try the following ... I believe it serves what you want 您可以尝试以下...我相信它可以满足您的需求

>>> # Given your sample data.
>>> ans = {}
>>> for (t, v, c, r, p) in zip(temp, volt, chan, rate, power):
...     if not t in ans:
...             ans[t] = {}
...     if not v in ans[t]:
...             ans[t][v] = {}
...     if not c in ans[t][v]:
...             ans[t][v][c] = {}
...     if not r in ans[t][v][c]:
...             ans[t][v][c][r] = p
>>> print ans
{25: {3.8: {1: {12: 13.2, 14: 15.3}, 6: {12: 13.8, 14: 15.1}}}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM