Home > Mobile >  Python merging two list into dictionaries, add values
Python merging two list into dictionaries, add values

Time:07-06

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.

CodePudding user response:

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

CodePudding user response:

One possible solution is to use dict.get with defaultvalue 0. For example:

stringlist = ["EL1", "EL2", "EL1", "EL3", "El4"]
integerlist = [1, 2, 12, 4, 5]

resultdictionary = {}
for s, i in zip(stringlist, integerlist):
    resultdictionary[s] = resultdictionary.get(s, 0)   i

print(resultdictionary)

Prints:

{'EL1': 13, 'EL2': 2, 'EL3': 4, 'El4': 5}

CodePudding user response:

The quickest way w/o imports would be like this:

stringlist = ["EL1", "EL2", "EL1", "EL3", "El4"]

integerlist = [1, 2, 12, 4, 5]

#Convert two Lists into Dictionary using zip()
mergeLists = dict(zip(stringlist, integerlist))
  • Related