2

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

2
  • 2
    Have you made any attempts to solve this issue? What exactly are you stuck on? Commented Mar 19, 2020 at 17:04
  • I tried to create the dictionary, but since some of the values ​​in the list are repeated, it only gave the dictionary the value saw first. For example, ` dict = {"DDS 500: {" A ": 300}, .. ` @jordanm Commented Mar 19, 2020 at 17:07

3 Answers 3

3

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}})
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.