Python Tutorial (33) – Example: Calculating the sum of dictionary values

Time: Column:Python views:292

Calculate the Sum of All Numeric Values in a Dictionary

In Python, you can calculate the sum of all numeric values in a dictionary by iterating through the dictionary and summing its values.

Example:

def returnSum(myDict): 
    # Initialize sum to 0
    sum = 0
    
    # Iterate through the dictionary
    for i in myDict: 
        sum = sum + myDict[i] 
      
    return sum

# Define a dictionary with numeric values
dict = {'a': 100, 'b': 200, 'c': 300} 

# Print the sum of values
print("Sum:", returnSum(dict))

Output:

Sum: 600

This example defines a dictionary with three key-value pairs, sums the values, and returns the total sum.