将多个列表映射到字典 [英] mapping multiple lists to dictionary

查看:157
本文介绍了将多个列表映射到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有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

想法来自相关问题的答案。)

这篇关于将多个列表映射到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆