python - 将多个列表映射到字典

标签 python list dictionary mapping

我有 5 个列表,我想将它们映射到分层字典。

假设我有:

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]

我想要的字典是这样的:

{25:{3.8:{1:{12:13.2,14:15.3},6:{12:13.8,14:15.1}}}}

基本上字典结构是:

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

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

最佳答案

这只是稍微测试了一下,但似乎可以解决问题。基本上,f 所做的是创建 defaultdictsdefaultdict

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

(思路借鉴自this answer to a related question。)

关于python - 将多个列表映射到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12590358/

相关文章:

Python人类可读的日期差异

python - 根据 Python 中的列表元素检查输入

list - 如何将文件中的列表添加到 Lisp

list - 是否有已知的网络爬虫列表?

swift - 使用枚举的默认值作为字典键而不显式转换为 String

c++ - std::map 或 std::list 的 mem_set

python - 从另一个字符串中删除一个字符串

python - 如何使用 python 找出 (windows) 内存映射文件是否已经存在

python - 为什么 numpy random.choice() 函数被停用了?

c++ - 为什么map在(switch)格外变成空的?