Home > Software engineering >  Multiple Nested dictionary From a loop
Multiple Nested dictionary From a loop

Time:08-25

I am trying to make a dependent nested dictionary from a loop. Suppose this is my list

for i in compatibility:
    print(i.os_id, i.python_id, i.ml_id)

If I print this one then I will get data something similar to this

output :

1 1 1
1 1 2
1 2 1
1 2 2
2 1 1
2 2 2
2 2 3

What I want is I want to make it a nested 3 level dictionary and for this output the dictionary will be something like this:

{1: {1: {1,2}, 2: {1,2}}, 2: {1: {1}, 2: {2,3}}}

How can I achieve this? Any help would be appreciated

CodePudding user response:

Based on comments I used lists in output:

data = [
    ["1", "1", "1"],
    ["1", "1", "2"],
    ["1", "2", "1"],
    ["1", "2", "2"],
    ["2", "1", "1"],
    ["2", "2", "2"],
    ["2", "2", "3"],
]

out = {}
for a, b, c in data:
    out.setdefault(a, {}).setdefault(b, []).append(c)
print(out)

Prints:

{"1": {"1": ["1", "2"], "2": ["1", "2"]}, "2": {"1": ["1"], "2": ["2", "3"]}}

If you want sets in output:

out = {}
for a, b, c in data:
    out.setdefault(a, {}).setdefault(b, set()).add(c)

EDIT: Removed collections.defaultdict

  • Related