简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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