Home > Blockchain >  How to create a nested dictionary in python with 6 lists
How to create a nested dictionary in python with 6 lists

Time:03-04

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

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:

{'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. Any tips would be greatly appreciated!

CodePudding user response:

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 zips, we could also do:

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

Output:

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

CodePudding user response:

Here's an approach that uses two dictionary comprehensions and 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}}
  • Related