Find the Sum of All Items in a Dictionary in Python

1. Introduction

Summing all items in a dictionary is a task that can be useful for statistical analysis, inventory calculations, or aggregating any numerical data that is stored as dictionary values.

The sum of all items in a dictionary refers to the total of the values associated with each key. In Python, this typically means iterating over the dictionary and adding up the values.

2. Program Steps

1. Initialize a dictionary with numerical values.

2. Iterate over the dictionary's values and calculate their sum.

3. Output the sum of the values.

3. Code Program

# Initialize the dictionary
my_dict = {'a': 100, 'b': 200, 'c': 300}

# Initialize a variable to hold the sum of the items
sum_of_items = 0

# Iterate over the dictionary's values and add them to the sum_of_items
for value in my_dict.values():
    sum_of_items += value

# Print the sum of the items
print(f"The sum of all items in the dictionary is: {sum_of_items}")

Output:

The sum of all items in the dictionary is: 600

Explanation:

1. my_dict is a dictionary containing three key-value pairs where the values are numerical.

2. sum_of_items is initialized to 0 and will accumulate the sum of the dictionary's values.

3. A for loop iterates over each value in the dictionary by calling my_dict.values().

4. Each value is added to sum_of_items within the loop.

5. After the loop completes, sum_of_items contains the sum of all values in my_dict.

6. The print statement then outputs this sum, showing that the total of all items in the given dictionary is 600.

Comments