Editor

Python Program to Find the Sum of All Values in a Dictionary

Beginner · Dictionaries

This program adds up all the values in a dictionary, for example a month of expenses stored as category and amount. It loops over the values only, since the keys are just labels.

Program

sum_of_dictionary_values.py
expenses = {"food": 2500, "travel": 1200, "books": 800, "phone": 499}
total = 0
for amount in expenses.values():
total += amount
print("Expenses:")
for item, amount in expenses.items():
print(f" {item:7} {amount:5}")
print("Total spent:", total)
Output
Expenses:
  food     2500
  travel   1200
  books     800
  phone     499
Total spent: 4999

How it works

  1. expenses.values() gives just the values, 2500, 1200, 800 and 499, without the keys.
  2. Each value is added to total, which starts at 0.
  3. The second loop uses items() to print each key with its value, and :5 right-aligns the numbers in a column.
  4. Every value must be a number; a text value would make the addition fail with a TypeError.

Other ways to write it

Using sum()

Using sum()
expenses = {"food": 2500, "travel": 1200, "books": 800, "phone": 499}
total = sum(expenses.values())
print("Total:", total)
print("Average per item:", total / len(expenses))
Output
Total: 4999
Average per item: 1249.75

sum() adds the values in one step, and dividing by len(expenses), the number of keys, gives the average.

When each value is a list

When each value is a list
marks = {"Riya": [88, 92, 79], "Arjun": [72, 65, 80]}
grand_total = 0
for name, scores in marks.items():
print(name, "total:", sum(scores))
grand_total += sum(scores)
print("Grand total:", grand_total)
Output
Riya total: 259
Arjun total: 217
Grand total: 476

Here each value is a list of marks, so sum(scores) totals one student and grand_total adds the students together.

Try it yourself

Add a "rent" expense of 6000 and check that the total goes up by exactly that amount.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises