Python
Dictionary
Sum
Coding
Programming

How to sum all the values in a dictionary?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Dictionaries are one of the most commonly used data structures in Python, and sooner or later you will need to aggregate the numbers stored inside one. Whether you are totaling up sales figures, counting inventory, or merging frequency tables, understanding the different ways to sum dictionary values will save you time and prevent subtle bugs.

Before jumping into techniques, it helps to know why Python provides a dedicated .values() method. Dictionaries store data as key-value pairs, and the values view gives you direct access to every stored value without forcing you to iterate over keys first. That design choice is what makes the one-liner approaches below both readable and efficient.

The Basic Approach with sum()

The simplest way to sum every value in a dictionary is to pass d.values() directly to the built-in sum() function.

python
sales = {"Monday": 150, "Tuesday": 230, "Wednesday": 180}
total = sum(sales.values())
print(total)  # 560

sum() accepts any iterable of numbers, and dict.values() returns exactly that. This runs in O(n) time where n is the number of keys, and it creates no intermediate list in Python 3 because .values() returns a view object.

Summing Values for Specific Keys

Sometimes you only care about a subset of keys. A generator expression lets you pick exactly which keys participate in the sum.

python
1budget = {"rent": 1200, "food": 400, "transport": 150, "entertainment": 200}
2essentials = {"rent", "food", "transport"}
3
4essential_total = sum(budget[k] for k in essentials if k in budget)
5print(essential_total)  # 1750

The if k in budget guard protects you from KeyError when the set of desired keys might not all be present in the dictionary.

Summing with Conditions

You can also filter by value rather than by key. A dictionary comprehension or generator expression inside sum() handles this cleanly.

python
1scores = {"Alice": 88, "Bob": 45, "Carol": 72, "Dave": 91}
2
3passing_total = sum(v for v in scores.values() if v >= 60)
4print(passing_total)  # 251 (Alice + Carol + Dave)

This pattern is especially useful for dashboards where you need aggregates like "total revenue from orders above a threshold."

Summing Nested Dictionaries

Real-world data is often nested. When each value is itself a dictionary, you need to decide which level to sum.

python
1quarterly_sales = {
2    "Q1": {"ProductA": 100, "ProductB": 200},
3    "Q2": {"ProductA": 150, "ProductB": 250},
4    "Q3": {"ProductA": 130, "ProductB": 180},
5}
6
7# Total across all quarters and products
8grand_total = sum(
9    val
10    for quarter in quarterly_sales.values()
11    for val in quarter.values()
12)
13print(grand_total)  # 1010
14
15# Total per quarter
16per_quarter = {q: sum(products.values()) for q, products in quarterly_sales.items()}
17print(per_quarter)  # {'Q1': 300, 'Q2': 400, 'Q3': 310}

The double for in the generator expression flattens the nested structure in a single pass.

Using collections.Counter for Addition

Counter is a dictionary subclass designed for counting. When you add two Counter objects together, matching keys are summed automatically.

python
1from collections import Counter
2
3store_a = Counter({"apples": 30, "bananas": 15, "oranges": 20})
4store_b = Counter({"apples": 10, "bananas": 25, "grapes": 5})
5
6combined = store_a + store_b
7print(combined)
8# Counter({'apples': 40, 'bananas': 40, 'oranges': 20, 'grapes': 5})
9
10print(sum(combined.values()))  # 105

This is the idiomatic way to merge frequency tables or inventory counts from multiple sources without writing manual loops.

Handling Non-Numeric Values

If your dictionary might contain strings, None, or mixed types, calling sum() directly will raise a TypeError. Defensive code filters or converts values first.

python
1raw_data = {"a": 10, "b": "twenty", "c": 30, "d": None}
2
3safe_total = sum(v for v in raw_data.values() if isinstance(v, (int, float)))
4print(safe_total)  # 40

If the strings represent numbers, convert them explicitly.

python
string_nums = {"x": "100", "y": "200", "z": "300"}
total = sum(int(v) for v in string_nums.values())
print(total)  # 600

Always validate or sanitize data before summing, especially when it comes from user input or external APIs.

Real-World Example: Monthly Sales Report

Here is a more complete example that ties several techniques together.

python
1from collections import Counter
2
3monthly_reports = [
4    {"widgets": 500, "gadgets": 300, "gizmos": 150},
5    {"widgets": 620, "gadgets": 280},
6    {"widgets": 450, "gadgets": 350, "gizmos": 200, "doohickeys": 80},
7]
8
9combined = Counter()
10for report in monthly_reports:
11    combined += Counter(report)
12
13print(dict(combined))
14# {'widgets': 1570, 'gadgets': 930, 'gizmos': 350, 'doohickeys': 80}
15print(f"Grand total units sold: {sum(combined.values())}")
16# Grand total units sold: 2930

Common Pitfalls

  • Calling sum() on the dictionary itself sums the keys, not the values, which causes a TypeError if keys are strings.
  • Forgetting .values() and writing sum(d) iterates over keys by default.
  • Mixed types in values will raise TypeError at runtime with no warning at definition time.
  • Floating-point precision can drift when summing many floats; use math.fsum() or decimal.Decimal when exactness matters.
  • Mutating the dictionary during iteration (adding or removing keys inside a generator passed to sum()) raises RuntimeError.

Summary

  • Use sum(d.values()) for a quick total of all values in a flat dictionary.
  • Use generator expressions inside sum() to filter by key or by value.
  • Flatten nested dictionaries with a double for in the generator.
  • Use collections.Counter addition to merge and sum multiple dictionaries idiomatically.
  • Guard against non-numeric values with isinstance checks or explicit conversion.
  • For high-precision work with floats, prefer math.fsum() over the built-in sum().

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.