Search code examples
pythondictionaryzip

Python - create dictionary from two lists with repeated elements


Trying to use zip() to create a dictionary from two lists (keys and values) where there is a repeated key element. What I want is for the dictionary to have a single key for the repeated element and for the corresponding value to be the sum of the repeated values.

lst1 = ['a', 'b', 'c', 'd', 'b']
lst2 = [2, 3, 4, 5, 6]
new_dictionary = dict(zip(lst1,lst2))
print(new_dictionary)

Actual output: {'a': 2, 'b': 6, 'c': 4, 'd': 5}

Desired output: {'a': 2, 'b': 9, 'c': 4, 'd': 5}


Solution

  • If you use defaultdict you can set the type to int. This will let you simply add to it:

    from collections import defaultdict
    
    new_dictionary = defaultdict(int)
    
    lst1 = ['a', 'b', 'c', 'd', 'b']
    lst2 = [2, 3, 4, 5, 6]
    
    for k, n in zip(lst1,lst2):
        new_dictionary[k] += n
        
    print(new_dictionary)
    # defaultdict(<class 'int'>, {'a': 2, 'b': 9, 'c': 4, 'd': 5})
    

    You could also use collections.Counter() the same way by simply using new_dictionary = Counter() instead.