In: Computer Science
Python pls
Create a function dict_sum. This function takes a dictionary and sums up the values in the dictionary.
For example:
dict1 = {1: {'una': 5, 'dos': 7, 'tres': 9, 'quar' : 11}, 2: {'dos':2, 'quar':4}, 3:{'una': 3, 'tres': 5}, 4:{'cin': 6}, 5:{'tres': 7 , 'cin': 8}}
dict2 = {300:{'s': 300}, 400:{'s': 100, 'g': 100, 'p': 100}, 500: {'s': 50 ,'m': 400, 'p':30, 'i': 50}, 600: {'s': 40, 'i': 400}, 700: {'m': 100, 'p': 50}}
def dict_sum(db):
should give output
output1 = {'una':values(int), 'dos': :values(int), 'tres':values(int), 'quar': values(int), 'cin': values(int)}
output2 = {'s':values(int),'g':values(int), 'm': values(int), 'p': values(int), 'i': values(int)}
The answer to this question is as follows:
The code is as follows:
dict1 = {1: {'una': 5, 'dos': 7, 'tres': 9, 'quar' : 11}, 2:
{'dos':2, 'quar':4}, 3:{'una': 3, 'tres': 5}, 4:{'cin': 6},
5:{'tres': 7 , 'cin': 8}}
result={}
for key,value in dict1.items():
for k,v in value.items():
if k not in result:
result[k]=v
else:
result[k]=result[k]+v
print(result)
The input and output are provided in the screenshot below: