How to Sum All Values in a Python Dictionary

If you need to sum all values in a Python dictionary, call sum(d.values()). It adds every value in one pass, and an empty dictionary simply gives 0:

total = sum(budget.values())

My test data is a household budget in US dollars, and I ran each script in a Command Prompt with Python 3.12.5.

In this tutorial, we’ll total a whole dictionary, fix the odd decimals floats produce, add up only some keys, and handle nested dictionaries, list values and values that aren’t numbers.

Sum all values in a dictionary with sum() and values()

values() returns a view of the values, and sum() walks it once. Format the result with :,.2f so money always shows two decimals:

budget = {"rent": 1450.00, "groceries": 386.45, "utilities": 142.10,
          "internet": 59.99, "gas": 61.30}

total = sum(budget.values())
print("Raw total:      ", total)
print(f"Monthly total:   ${total:,.2f}")
print("Empty dict sum: ", sum({}.values()))

Output:

Raw total:       2099.84
Monthly total:   $2,099.84
Empty dict sum:  0
Command Prompt output of Python sum() adding all values of a budget dictionary and printing the total in USD
The raw float total, the same total formatted as dollars with two decimals, and 0 for an empty dictionary.

sum() also takes a start value and works on any iterable; my guide to the Python sum() function covers those options.

Why does my dictionary total print 0.30000000000000004?

Floats are stored in binary, so 0.10 and 0.20 can’t be held exactly. Adding them leaves a tiny error that shows up when you print the raw number:

from decimal import Decimal
import math

fees = {"card": 0.10, "service": 0.20}
print("sum():        ", sum(fees.values()))
print("round(x, 2):  ", round(sum(fees.values()), 2))
print("math.fsum():  ", math.fsum(fees.values()))

cents = {"card": Decimal("0.10"), "service": Decimal("0.20")}
print("Decimal sum:  ", sum(cents.values()))
print(f"Printed:       ${sum(fees.values()):.2f}")

Output:

sum():         0.30000000000000004
round(x, 2):   0.3
math.fsum():   0.30000000000000004
Decimal sum:   0.30
Printed:       $0.30
Command Prompt output comparing Python sum, round, math.fsum and Decimal when adding float dictionary values
sum() and math.fsum() both print 0.30000000000000004; round() gives 0.3, while Decimal and the :.2f print show 0.30.

math.fsum() doesn’t fix this case. It adds the floats exactly, but 0.10 was never exact to begin with.

For display, :.2f is enough. If you store or compare totals, use round(total, 2), and keep real money in Decimal built from strings. Floating-point numbers in Python explains why.

Sum only some values in a dictionary

A generator expression inside sum() lets you choose the keys, or keep only values that pass a test:

budget = {"rent": 1450.00, "groceries": 386.45, "utilities": 142.10,
          "internet": 59.99, "gas": 61.30}

bills = ("rent", "utilities", "internet")
fixed = sum(budget[k] for k in bills)
small = sum(v for v in budget.values() if v < 100)
print(f"Fixed bills:      ${fixed:,.2f}")
print(f"Items under $100: ${small:,.2f}")

Output:

Fixed bills:      $1,652.09
Items under $100: $121.29

If you’d rather build the smaller dictionary first and keep it, see filtering a Python dictionary. To find the biggest item instead of a total, use max value in a dictionary.

Sum nested dictionaries, list values and a list of dictionaries

When each value is itself a dictionary or a list, sum the inner values first, then the outer ones:

sales = {
    "Texas":   {"Q1": 18250.50, "Q2": 21400.25},
    "Ohio":    {"Q1": 9875.00,  "Q2": 11020.40},
    "Florida": {"Q1": 15300.10, "Q2": 14990.90},
}
by_state = {state: sum(q.values()) for state, q in sales.items()}
for state, amount in by_state.items():
    print(f"{state:<8} ${amount:>10,.2f}")
print(f"{'All':<8} ${sum(by_state.values()):>10,.2f}")

tips = {"Mon": [12.50, 8.25], "Tue": [15.00], "Wed": [9.75, 6.40, 11.10]}
print(f"Tips this week: ${sum(sum(day) for day in tips.values()):.2f}")

orders = [{"item": "mug", "price": 14.99}, {"item": "tee", "price": 24.50},
          {"item": "cap", "price": 19.95}]
print(f"Cart total:     ${sum(o['price'] for o in orders):.2f}")

Output:

Texas    $ 39,650.75
Ohio     $ 20,895.40
Florida  $ 30,291.00
All      $ 90,837.15
Tips this week: $63.00
Cart total:     $59.44
Command Prompt output of Python summing nested dictionary sales by state, list values and a list of dictionaries
Each state’s two quarters are added, then all states; the list values and the cart use the same nested sum() pattern.

The by_state line is a dict comprehension. If the loop form reads easier, here’s how to create a dictionary in Python using a for loop. Values that hold lists are covered in a dictionary with multiple values per key.

What if some dictionary values aren’t numbers?

sum() raises a TypeError on strings or None. Convert or skip those values inside the generator:

order = {"subtotal": 48.97, "shipping": "5.99", "discount": None}
try:
    print(sum(order.values()))
except TypeError as err:
    print("TypeError:", err)

total = sum(float(v) for v in order.values() if v is not None)
print(f"Cleaned total: ${total:.2f}")

Output:

TypeError: unsupported operand type(s) for +: 'float' and 'str'
Cleaned total: $54.96

Data from forms and CSV files often arrives as text, so clean it once and update the values in the dictionary rather than converting on every total.

Still working with dictionaries? These pick up where this one stops:

Frequently asked questions

How do I sum all values in a Python dictionary?

Use sum(d.values()). It returns 0 for an empty dictionary.

How do I sum the values of certain keys only?

Use a generator expression, such as sum(d[k] for k in keys).

Why is my dictionary total 0.30000000000000004?

That’s float rounding error. Print with :.2f, use round(total, 2), or store money as Decimal.

How do I sum values in a nested dictionary?

Sum the inner dictionaries first: sum(sum(v.values()) for v in d.values()).

How do I sum a key across a list of dictionaries?

Use sum(row["price"] for row in rows).

Where is sum() documented?

See sum() in the Python docs.