Issue
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
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)
Answered By - Ȇ͉͖̙ͅn̵͔̒i̝̒́͘g̦̪͐̈́m̨̒̏͐͠a̝̒̑
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.