简体   繁体   中英

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}

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM