简体   繁体   English

如何使用 6 个列表在 python 中创建嵌套字典

[英]How to create a nested dictionary in python with 6 lists

I am looking to extend the approach taken here but for the case of six or more lists: How to Create Nested Dictionary in Python with 3 lists我希望扩展此处采用的方法,但对于六个或更多列表的情况: How to Create Nested Dictionary in Python with 3 lists

a = ['A', 'B', 'C', 'D']
b = [1, 2, 3, 4]
c = [9, 8, 7, 6]
d = [0, 3, 5, 7]
e = [11, 13, 14, 15]

Desired output:所需的 output:

{'A':{1 :9, 0:11} , 'B':{2:8, 3:13}, 'C':{3:7, 5:13} , 'D':{4:6, 7:15}}

Here's what I've tried so far:到目前为止,这是我尝试过的:

out = dict([[a, dict([map(str, i)])] for a, i in zip(a, zip(zip(b, c), zip(d,e) ))])

The output is close, but it's not quite what I'm looking for. output 很接近,但它不是我要找的。 Any tips would be greatly appreciated!任何提示将非常感谢!

Maybe something like:也许是这样的:

out = {k: {k1: v1, k2: v2} for k, k1, v1, k2, v2 in zip(a, b, c, d, e)}

If we want to use excessive number of zip s, we could also do:如果我们想使用过多的zip s,我们也可以这样做:

out = {k: dict(v) for k,v in zip(a, zip(zip(b, c), zip(d, e)))}

Output: Output:

{'A':{1 :9, 0:11} , 'B':{2:8, 3:13}, 'C':{3:7, 5:13} , 'D':{4:6, 7:15}}

Here's an approach that uses two dictionary comprehensions and zip() :这是一种使用两个字典理解和zip()的方法:

result = {key: { inner_key: inner_value for inner_key, inner_value in value} 
    for key, value in zip(a, zip(zip(b, c), zip(d, e)))
}

print(result)

The result, using the lists in the original question:结果,使用原始问题中的列表:

{'A': {1: 9, 0: 11}, 'B': {2: 8, 3: 13}, 'C': {3: 7, 5: 14}, 'D': {4: 6, 7: 15}}

You could try NestedDict .你可以试试NestedDict First install ndicts首先安装ndicts

pip install ndicts

Then然后

from ndicts.ndicts import NestedDict

a = ['A', 'B', 'C', 'D']
b = [1, 2, 3, 4]
c = [9, 8, 7, 6]
d = [0, 3, 5, 7]
e = [11, 13, 14, 15]

# Create levels and values
level_0 = a * 2
level_1 = b + d
values = c + e

# Initialize the keys of a NestedDict
nd = NestedDict.from_tuples(*zip(level_0, level_1))

# Assign values
for key, value in zip(nd, values):
    nd[key] = value

If you need the result as a dictionary如果您需要将结果作为字典

result = nd.to_dict()

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

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