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.
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.
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.
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.
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.
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.
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.
If the strings represent numbers, convert them explicitly.
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.
Common Pitfalls
- Calling
sum()on the dictionary itself sums the keys, not the values, which causes aTypeErrorif keys are strings. - Forgetting
.values()and writingsum(d)iterates over keys by default. - Mixed types in values will raise
TypeErrorat runtime with no warning at definition time. - Floating-point precision can drift when summing many floats; use
math.fsum()ordecimal.Decimalwhen exactness matters. - Mutating the dictionary during iteration (adding or removing keys inside a generator passed to
sum()) raisesRuntimeError.
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
forin the generator. - Use
collections.Counteraddition to merge and sum multiple dictionaries idiomatically. - Guard against non-numeric values with
isinstancechecks or explicit conversion. - For high-precision work with floats, prefer
math.fsum()over the built-insum().
Related reading
- How to switch position of two items in a Python list?
- How to take the first N items from a generator or list?
- How to tell if an array is a permutation in On?
- How to test if a dictionary contains a specific key?
- How to suppress or capture the output of subprocess.run?
- How to suppress Pandas Future warning?
- How to trace the path in a Breadth-First Search?
- How to traverse a tree from sklearn AgglomerativeClustering?

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 courseTrack 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.