The Nephilim
The Nephilim

Reputation: 11

Merging and appending dictionaries

I am tasked with taking dictionaries of classes with students names and there grades for the each class like below


History = {"bob": 20, "alex" :80}

Maths = {"harry": 50, "bob" : 90}

english = {"alex" : 40, "lee" : 20}

art = {"lee" : 70, "harry" :40}

and then putting the student scores from each class into one final dictionary as below


Final = {"alex":80,40 , "bob":20,90 , "harry":50,40 , "lee":20,70}

I have successfully managed to put all the classes in to one big dictionary but I cant manage to get the multiple value for each of the student names. The closest I get is puting them all the dictionaries in a list like below


lst = [{"bob": 20, "alex" :80},{"harry": 50, "bob" : 90},{"alex" : 40, "lee" : 20},{"lee" : 70, "harry" :40}]

after this I don't know what to do. I assume somehow loop through each of the key value pairs and put it in to a dictionary. Then if a key value is in the new dictionary you somehow add the value on to the existing key, but I cant seem to figure it out.Any help would be great

Upvotes: 1

Views: 33

Answers (3)

final_dict={}

for el in lst:
    for person,value in el.items():
        if person not in final_dict:
            final_dict[person]=[value]
        else:
            final_dict[person].append(value)

Output:

{'bob': [20, 90], 'alex': [80, 40], 'harry': [50, 40], 'lee': [20, 70]}

Upvotes: 0

azro
azro

Reputation: 54148

You may use a collections.defaultdict, then for each student, append its grade

result = defaultdict(list)
for subject in History, Maths, english, art:
    for student, grade in subject.items():
        result[student].append(grade)

print(result)  # {'bob': [20, 90], 'alex': [80, 40], 'harry': [50, 40], 'lee': [20, 70]}

Upvotes: 1

Arty
Arty

Reputation: 16737

Try it online!

History = {"bob": 20, "alex" :80}
Maths = {"harry": 50, "bob" : 90}
english = {"alex" : 40, "lee" : 20}
art = {"lee" : 70, "harry" :40}

final = {}
for d in [History, Maths, english, art]:
    for k, v in d.items():
        if k not in final:
            final[k] = []
        final[k].append(v)
print(final)

Output:

{'bob': [20, 90], 'alex': [80, 40], 'harry': [50, 40], 'lee': [20, 70]}

Upvotes: 0

Related Questions