snndmnsz
snndmnsz

Reputation: 25

Python creating nested dictionary from a List with repeating keys

I am trying to convert the list to a dictionary. I have a list of list like this and some of the first values of mini lists are repeating:

list = [["DDS 500","A",300], ["DDS 500","B",100], ["AGB 850","C",250], ["AGB 850","B",350], ["UNI 100","D",900]]

The first value of mini lists will be key . Then, for each mini list second and third value will be the "value" for that key and the values also should be a dictionary. As a result, Final dictionary should be like this:

dict = { "DDS 500":{"A":300,"B":100}, "AGB 850":{"C":250,"B":350}, "UNI 100":{"D":900} }

Upvotes: 2

Views: 123

Answers (3)

Alain T.
Alain T.

Reputation: 42143

You could do it in two steps: 1) create the dictionary with all keys and and empty dictionary as value, 2) merge the values as dictionaries into each key:

lst = [["DDS 500","A",300], ["DDS 500","B",100], ["AGB 850","C",250], ["AGB 850","B",350], ["UNI 100","D",900]]

d = { k:dict() for k,*_ in lst }
for k,*v in lst: d[k].update(dict([v]))

output:

print(d)

# {'DDS 500': {'A': 300, 'B': 100}, 'AGB 850': {'C': 250, 'B': 350}, 'UNI 100': {'D': 900}}

Upvotes: 1

kederrac
kederrac

Reputation: 17322

you can use dict.setdefault if you do not want to import any module:

result = {}

for k1, k2, v in my_list:
    result.setdefault(k1, {})[k2] = v
result

output:

{'DDS 500': {'A': 300, 'B': 100},
 'AGB 850': {'C': 250, 'B': 350},
 'UNI 100': {'D': 900}}

Upvotes: 1

Ch3steR
Ch3steR

Reputation: 20669

You can use collections.defaultdict

from collections import defaultdict

lst= [["DDS 500","A",300], ["DDS 500","B",100], ["AGB 850","C",250], ["AGB 850","B",350], ["UNI 100","D",900]]

out=defaultdict(dict)

for k,ik,iv in lst:
    out[k].update({ik:iv})

Output:

defaultdict(dict,
            {'DDS 500': {'A': 300, 'B': 100},
             'AGB 850': {'C': 250, 'B': 350},
             'UNI 100': {'D': 900}})

Upvotes: 3

Related Questions