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 tutorial, you will learn how to Display Prime Numbers Between Two Intervals using the if and else...
In this python tutorial, you will learn how to Calculate Standard Deviation with built in functions of the python programming...
In this Python program, we will convert temperature values from Celsius to Fahrenheit. The Celsius and Fahrenheit scales are two...