1

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!

BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
Sjoseph
  • 853
  • 2
  • 14
  • 23
  • 1
    Why are you using `map(str, i)`? Nothing in your question requires converting to strings. And why put the map inside `[]`? – Barmar Mar 03 '22 at 17:56
  • If you did that because the linked question uses it, notice that they wanted to convert the integers in the original lists into strings in the dictionaries. That part of the solution has nothing to do with nesting, it's just for that conversion. Don't just copy code without understanding what it's doing and why. – Barmar Mar 03 '22 at 17:59
  • 1
    If you replace `[a, dict([map(str, i)])]` with `(a, dict(i))` your code works. –  Mar 03 '22 at 18:02

3 Answers3

6

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

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}}
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
0

You could try NestedDict. First install 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()
edd313
  • 1,109
  • 7
  • 20