12
Question Question 12
A dictionary D1 has values in the form of lists of numbers. Write a program to create a new dictionary D2 having same keys as D1 but values as the sum of the list elements e.g.,
D1 = {'A' : [1, 2, 3] , 'B' : [4, 5, 6]}
then
D2 is {'A' :6, 'B' : 15}
Solution
D1 = eval(input("Enter a dictionary D1: "))
print("D1 =", D1)
D2 = {}
for key in D1:
num = sum(D1[key])
D2[key] = num
print(D2)Output
Enter a dictionary D1: {'A' : [1, 2, 3] , 'B' : [4, 5, 6]}
D1 = {'A': [1, 2, 3], 'B': [4, 5, 6]}
{'A': 6, 'B': 15}