How to Sum All Values in a Python Dictionary?

As a Python developer working on various projects for my clients across the USA I came across a scenario where I needed to sum all values in a dictionary. After researching I found two efficient methods to accomplish this task. In this tutorial, I will explain how to sum all values in a Python dictionary with suitable examples and screenshots.

Sum All Values in a Python Dictionary

Before getting into summing values, let’s quickly recap what Python dictionaries are. A dictionary is a collection of key-value pairs, where each key is unique and associated with a specific value. Dictionaries are defined using curly braces {} and consist of comma-separated key-value pairs. For example:

sales_data = {
    "New York": 5000,
    "Los Angeles": 7500,
    "Chicago": 4200,
    "Houston": 6100
}

In this example, we have a dictionary called sales_data representing the sales figures for different cities in the USA.

Read How to Slice a Dictionary in Python?

Method 1. Use sum() and values()

One of the simplest ways to sum all the values in a dictionary is by using the built-in sum() function in combination with the values() method. The values() method returns a view object containing all the values of the Python dictionary. Here’s how you can use them together:

total_sales = sum(sales_data.values())
print("Total sales:", total_sales)

Output:

Total sales: 22800

I executed the above example code and added the screenshot.

Sum All Values in a Python Dictionary

In this code snippet, sales_data.values() returns a view object containing all the values of the sales_data dictionary. The sum() function then calculates the sum of all these values, giving us the total sales across all cities.

Check out Python Dictionary Update

Method 2. Use a Loop

Another approach to summing Python dictionary values is by using a loop to iterate over the key-value pairs and accumulate the sum. This can be useful if you need more control over the summing process or want to perform additional operations along the way. Here’s an example:

total_sales = 0
for city, sales in sales_data.items():
    total_sales += sales
print("Total sales:", total_sales)

Output:

Total sales: 22800

I executed the above example code and added the screenshot.

How to Sum All Values in a Python Dictionary

In this code, we initialize a variable total_sales to keep track of the running sum. We then use the items() method to iterate over the key-value pairs of the sales_data dictionary. For each pair, we add the sales value to total_sales. Finally, we print the total sales amount.

Read Python Copy Dict Without One Key

Example: Analyze Sales Data

Let’s consider a more complex example where we have a dictionary containing sales data for different products in various regions of the USA. We want to calculate the total sales for each region and the overall total sales. Here’s how we can achieve that:

sales_data = {
    "East": {
        "Product A": 10000,
        "Product B": 5000,
        "Product C": 8000
    },
    "West": {
        "Product A": 12000,
        "Product B": 6000,
        "Product C": 9000
    },
    "South": {
        "Product A": 8000,
        "Product B": 4000,
        "Product C": 6000
    }
}

# Calculate total sales for each region
for region, product_sales in sales_data.items():
    region_total = sum(product_sales.values())
    print(f"Total sales in {region}: ${region_total}")

# Calculate overall total sales
overall_total = sum(sum(product_sales.values()) for product_sales in sales_data.values())
print("Overall total sales: $", overall_total)

Output:

Total sales in East: $23000
Total sales in West: $27000
Total sales in South: $18000
Overall total sales: $ 68000

I executed the above example code and added the screenshot.

Sum All Values in a Python Dictionary example

In this example, we have a nested dictionary sales_data where the outer keys represent regions and the inner keys represent products. We first iterate over the regions using a loop and calculate the total sales for each region by summing the values of the inner dictionary using sum(product_sales.values()). We print the total sales for each region.

To calculate the overall total sales, we use a nested sum() function along with a generator expression. The generator expression sum(product_sales.values()) calculates the sum of values for each inner dictionary, and the outer sum() function sums up all these totals to give us the overall total sales.

Check out Python Dictionary contains

Conclusion

In this tutorial, I helped you to learn how to sum all values in a Python dictionary. I explained how to use the sum() function with the values() method to sum, and how to use a loop to sum values. I also covered a real-time example to analyze sales data.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.