Issue
Given the two following lists, one containing strings, one integers, how can I merge these two lists into a dictionary while ADDING the values for duplicate keys?
stringlist = ["EL1", "EL2", "EL1", "EL3", "El4"]
integerlist = [1, 2, 12, 4, 5]
So in the final dictionary I'd like EL1 to be 13, because it also contains 1 and 12.
resultdictionary = {}
for key in appfinal:
for value in amountfinal:
resultdictionary[key] = value
amountfinal.remove(value)
break
In this case, result dictionary removes any duplicate keys, but takes the last value that matches those keys. So, EL1 would be 12.
Any ideas? Thank you.
Solution
Use defaultdict()
to create a dictionary that automatically creates keys as needed.
Use zip()
to loop over the two lists together.
from collections import defaultdict
resultdictionary = defaultdict(int)
for key, val in zip(stringlist, integerlist):
resultdictionary[key] += val
Answered By - Barmar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.