Python Program to Find the Sum of All the Items in a Dictionary

In this Python program, we’ll create a program to find the sum of all the values in a dictionary. Given a dictionary with numeric values, the program will calculate and display the sum of those values.

Problem Statement:

Given a dictionary containing numeric values, we want to calculate the sum of all the values in the dictionary.

Python Program to Find the Sum of All the Items in a Dictionary

def calculate_sum(dictionary):
    total_sum = sum(dictionary.values())
    return total_sum

def main():
    data = {
        'item1': 10,
        'item2': 20,
        'item3': 30,
        'item4': 40,
        'item5': 50
    }

    result = calculate_sum(data)
    print("Sum of all items:", result)

if __name__ == "__main__":
    main()

How it Works:

  1. We define a function calculate_sum that takes a dictionary as its parameter.
  2. Inside the calculate_sum function, we use the sum() function along with the values() method of the dictionary to calculate the sum of all the values in the dictionary.
  3. The main() function contains a sample dictionary named data with numeric values.
  4. We call the calculate_sum() function with the data dictionary as an argument and store the result in the result variable.
  5. Finally, we print out the sum of all the items in the dictionary.

Input/Output:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...