How to Increment a Value in a Python Dictionary

To increment a value in a Python dictionary, write d[key] += 1 when the key already exists. If it might be missing, use d[key] = d.get(key, 0) + 1, which starts new keys at zero instead of raising a KeyError:

visits["blog"] += 1                          # key exists
visits["faq"] = visits.get("faq", 0) + 1     # key may be new

Every output here is from a real run on Python 3.12.5, using page visits, store orders and sales totals in US dollars.

You’ll see get(), setdefault(), defaultdict, Counter and nested dictionaries.

Increment an existing dictionary value with +=

When the key’s there, += reads the value, adds to it and stores it back. A missing key isn’t so lucky:

visits = {"home": 120, "pricing": 45, "blog": 300}
visits["pricing"] += 1
print(visits)

try:
    visits["careers"] += 1
except KeyError as err:
    print("KeyError:", err)

Output:

{'home': 120, 'pricing': 46, 'blog': 300}
KeyError: 'careers'

That KeyError is the whole reason the other methods exist. If you want to test for the key first, my guide on checking whether a Python dictionary contains a key shows the options.

Increment a key that may not exist with dict.get()

get(key, 0) returns the current value, or 0 for a new key, so one line handles both cases. Here it counts orders and dollars per state:

sales = [("2026-03-02", "Texas", 19.99), ("2026-03-02", "Ohio", 5.50),
         ("2026-03-03", "Texas", 42.25), ("2026-03-03", "Florida", 12.00)]

orders = {}
totals = {}
for day, state, amount in sales:
    orders[state] = orders.get(state, 0) + 1
    totals[state] = round(totals.get(state, 0) + amount, 2)

print(orders)
for state, total in totals.items():
    print(f"{state}: ${total:,.2f}")

Output:

{'Texas': 2, 'Ohio': 1, 'Florida': 1}
Texas: $62.24
Ohio: $5.50
Florida: $12.00
Command Prompt output of Python dict.get() counting orders per state and adding USD sales totals
Texas gets two orders and a combined total, while Ohio and Florida each start at zero and get one order.

I round each total to two decimals so float noise doesn’t show up in dollar figures. To print them in order, see sorting a Python dictionary.

Increment with setdefault() or an if-in check

setdefault(key, 0) inserts the key only when it’s missing, so += can’t fail. The if key in d version is easier for beginners to read:

tickets = {}
for agent in ["Emily", "James", "Emily"]:
    tickets.setdefault(agent, 0)
    tickets[agent] += 1
print(tickets)

if "Olivia" in tickets:
    tickets["Olivia"] += 1
else:
    tickets["Olivia"] = 1
print(tickets)

Output:

{'Emily': 2, 'James': 1}
{'Emily': 2, 'James': 1, 'Olivia': 1}

Both take two steps where get() takes one, so you’ll see them less. For more ways to add keys, read adding items to a Python dictionary.

Count items with defaultdict(int)

defaultdict(int) calls int(), which returns 0, whenever you touch a missing key. That lets you write counts[w] += 1 with no checks at all:

from collections import defaultdict

words = "the cat and the hat and the bat".split()
counts = defaultdict(int)
for w in words:
    counts[w] += 1

print(dict(counts))
print(len(counts), counts["dog"], len(counts))

Output:

{'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}
5 0 6
Command Prompt output of Python defaultdict(int) counting words and adding a missing key when read
The word counts come out right, and simply reading counts["dog"] grows the dictionary from five keys to six.

That last line is the trap: reading a missing key adds it, so you should test with key in counts. The Python dict() function converts it back to a plain dictionary.

Increment counts with collections.Counter

Counter is a dictionary built for tallies. Missing keys read as 0, update() adds instead of replacing, and most_common() ranks them:

from collections import Counter

clicks = Counter(["home", "blog", "home", "pricing", "home"])
clicks["blog"] += 1
clicks.update(["pricing", "pricing"])
clicks.update({"home": 5})

print(clicks)
print(clicks.most_common(2))
print(clicks["careers"], "careers" in clicks)

Output:

Counter({'home': 8, 'pricing': 3, 'blog': 2})
[('home', 8), ('pricing', 3)]
0 False
Command Prompt output of Python Counter incremented with +=, update() with a list and a dict, and most_common
The home page ends up on top after update({"home": 5}), and the missing careers key reads as 0 without being added.

Unlike defaultdict, a Counter doesn’t insert keys you only read. Counting the keys and values themselves is covered in counting items in a Python dictionary.

How do I increment a value in a nested dictionary?

For counts grouped by two keys, like visits per day, nest a defaultdict(int) inside another defaultdict. With plain dicts, setdefault(day, {}) returns the inner dict to update:

from collections import defaultdict

log = [("2026-04-01", "home"), ("2026-04-01", "blog"),
       ("2026-04-02", "home"), ("2026-04-01", "home")]

visits = defaultdict(lambda: defaultdict(int))
for day, page in log:
    visits[day][page] += 1
print({day: dict(pages) for day, pages in visits.items()})

plain = {}
for day, page in log:
    pages = plain.setdefault(day, {})
    pages[page] = pages.get(page, 0) + 1
print(plain)

Output:

{'2026-04-01': {'home': 2, 'blog': 1}, '2026-04-02': {'home': 1}}
{'2026-04-01': {'home': 2, 'blog': 1}, '2026-04-02': {'home': 1}}
Command Prompt output of Python nested dictionary page visits per day built with defaultdict and with setdefault
Both approaches give the same visits per day: two home visits and one blog visit on April 1, and one home visit on April 2.

Lists inside dictionaries follow the same pattern; see a Python dictionary of lists.

Dictionary increment methods compared

MethodMissing keyBest for
d[k] += 1KeyErrorKeys you know exist
d.get(k, 0) + 1Starts at 0Plain dicts
defaultdict(int)Inserts 0 on readCounting loops
CounterReads 0, no insertTallies and top-N

Want to keep going with dictionaries? Try one of these:

Frequently asked questions

How do I increment a dictionary value by 1 in Python?

Use d[key] += 1 if the key exists, or d[key] = d.get(key, 0) + 1 if it might not.

Why do I get a KeyError when I increment a dictionary value?

+= reads the old value first, so the key must exist. Use get() or a defaultdict.

Can I increment a dictionary value by a decimal amount?

Yes. d[k] = round(d.get(k, 0) + 19.99, 2) adds dollars and keeps two decimal places.

Is Counter better than defaultdict(int)?

For counting, usually: it has most_common() and doesn’t insert keys you only read.

How do I increment values in a nested dictionary?

Use defaultdict(lambda: defaultdict(int)), or setdefault() plus get().

Where is defaultdict documented?

See collections.defaultdict in the Python docs.