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
CodePudding user response:
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)
CodePudding user response:
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_)
CodePudding user response:
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)
CodePudding user response:
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}