-2

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}

TheOneMusic
  • 1,776
  • 3
  • 15
  • 39
wrybosome
  • 3
  • 2
  • Does this answer your question? [Convert two lists into a dictionary](https://stackoverflow.com/questions/209840/convert-two-lists-into-a-dictionary) – Mehdi Zare Jul 19 '20 at 17:28

2 Answers2

2

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.

Mark
  • 90,562
  • 7
  • 108
  • 148
0

Here's a way:

lst1 = ['a', 'b', 'c', 'd', 'b']
lst2 = [2, 3, 4, 5, 6]
new_dictionary = {}

for key, value in zip(lst1, lst2):
    if key in new_dictionary:
        new_dictionary[key] += value
    else:
        new_dictionary[key] = value

print(new_dictionary)
TheOneMusic
  • 1,776
  • 3
  • 15
  • 39