Write a Python Program to Sum All The Items in a Dictionary

Hey Guys, in this article we will explore how to write a Python program to sum all the items in a dictionary. 

Lets take an example of fruit stall, where multiple fruits are kept for display with their cost. In order to store this type of data structure where key is fruit and value is the cost ,we will require a dictionary.

Lets take empty dictionary, ask user to fill the dictionary by asking input, then try finding the sum and display the output.

 

Title : Write a Python Program to Sum All The Items in a Dictionary


Accepting Dictionary Items from User Input


In this first part, we'll prompt the user to enter dictionary length, then using the for loop we will as user to enter key-value pairs of dictionary then store it into dictionary.


user_dict = {}

dict_length = int(input("Enter the length of the dictionary: "))

for _ in range(dict_length):
    key = input("Enter key: ")
    value = int(input("Enter value: "))
    user_dict[key] = value
 





Summing All Items in the Dictionary


Once we get all the items of dictionary we will iterate all the items of dictionary using for loop and then calculate the sum of all its values, once for loop is complete will print the dictionary and the sum of dictionary values.


total_sum = 0
for value in user_dict.values():
    total_sum += value

print("\nYour dictionary:", user_dict)
print("Sum of all values in the dictionary:", total_sum)v
 






Final Code



user_dict = {}

dict_length = int(input("Enter the length of the dictionary: "))

for _ in range(dict_length):
    key = input("Enter key: ")
    value = int(input("Enter value: "))
    user_dict[key] = value

total_sum = 0
for value in user_dict.values():
    total_sum += value

print("\nYour dictionary:", user_dict)
print("Sum of all values in the dictionary:", total_sum)
 




Output :



Enter the length of the dictionary: 4

Enter key: apple
Enter value: 5

Enter key: banana
Enter value: 10

Enter key: orange
Enter value: 8

Enter key: pineapple
Enter value: 3

Your dictionary: {'apple': 5, 'banana': 10, 'orange': 8, 'pineapple': 3}
Sum of all values in the dictionary: 26
 




Conclusion

In the above python program we accepted the dictionary items from the user and then calculated the sum of dictionary items and finally printed it.

Comment down below if you have any queries regarding the above python program.

Post a Comment

0 Comments