Perform Mathematical Operations on Dictionary Values in Python

Performing mathematical operations on dictionary values allows you to manipulate numerical data stored in the dictionary. In this blog post, we will explore different methods to perform mathematical operations on dictionary values in Python.

Method 1: Using a loop

# Method 1: Using a loop
my_dict = {"a": 10, "b": 5, "c": 20, "d": 15}
result = 0
for value in my_dict.values():
    result += value

print("Sum of Values:", result)

# Other mathematical operations such as finding the average, maximum, or minimum can also be performed using a loop.

Output:

Sum of Values: 50

Method 2: Using the built-in sum() function

# Method 2: Using the built-in sum() function
my_dict = {"a": 10, "b": 5, "c": 20, "d": 15}
result = sum(my_dict.values())

print("Sum of Values:", result)

# Other mathematical operations such as finding the average, maximum, or minimum can also be performed using the appropriate functions.

Output:

Sum of Values: 50