'How to add values of a key without losing any value in dictionary python when merging two list as dictionary?
I have two list of dictionaries which look like the following:
name = ['A','A','B','B','C','D','D','D']
num = [10, 20, 30, 40, 50, 60, 70, 80]
I want to merge them as 'name' for key and 'num' for value of the dictionary. But for each key if it has more than one value I want to add them without losing any 'num'. I tried to do it as
dict={}
for key,value in zip(name,num):
if key not in dict:
dict[key]=[value]
else:
dict[key].append(value)
print(dict)
I got output like
{'A': [10, 20], 'B': [30, 40], 'C': [50], 'D': [60, 70, 80]}
I want the final output to be like:
{'A': 30, 'B': 70, 'C': 50, 'D': 210}
Here every item for each key will be added rather than showing the list. How can I solve this?
Thanks
Solution 1:[1]
Try this:
name = ['A', 'A', 'B', 'B', 'C', 'D', 'D', 'D']
num = [10, 20, 30, 40, 50, 60, 70, 80]
dict = {}
for key, value in zip(name, num):
if key not in dict:
dict[key] = value
else:
dict[key] += value
print(dict)
Solution 2:[2]
instead of appending you need to add values
dict_={}
for key,value in zip(name,num):
if key not in dict_:
dict_[key]=value
else:
dict_[key]=dict_[key]+value
print(dict_)
Solution 3:[3]
Instead of appending the values of same key to a list, just add them while iterating.
Something like below.
name = ['A','A','B','B','C','D','D','D']
num = [10, 20, 30, 40, 50, 60, 70, 80]
dict={}
for key,value in zip(name,num):
if key not in dict:
dict[key]=value
else:
dict[key]+=value
print(dict)
Solution 4:[4]
Consider using collections.Counter:
from collections import Counter
name = ['A', 'A', 'B', 'B', 'C', 'D', 'D', 'D']
num = [10, 20, 30, 40, 50, 60, 70, 80]
c = Counter()
for key, value in zip(name, num):
c[key] += value
d = dict(c)
print(d)
from collections import defaultdict
name = ['A', 'A', 'B', 'B', 'C', 'D', 'D', 'D']
num = [10, 20, 30, 40, 50, 60, 70, 80]
d = defaultdict(int)
for key, value in zip(name, num):
d[key] += value
d = dict(d)
print(d)
Output:
{'A': 30, 'B': 70, 'C': 50, 'D': 210}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Í›Ì͔̲̲̑̑̒̅ͅ ̴͈̮͉͉͛̀̒͋̒ ̲̎̅̽̑̀̿ |
| Solution 2 | sahasrara62 |
| Solution 3 | Rohit Babu |
| Solution 4 |
