October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk2 min

How to Increment a Value in a Python Dictionary

Use += for a value under a known key, get() plus assignment when it may be missing, and defaultdict(int) or Counter for repeated counting.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For an existing key, use d[key] += amount. If the key might be missing and should start at zero, use d[key] = d.get(key, 0) + amount. For repeated accumulation, defaultdict(int) or Counter can avoid a separate existence check.

Increment a value when the key already exists

Use the key to read its current value, add the amount, and assign the result back to that key:

d = {"apples": 4}
d["apples"] += 1

print(d)  # {'apples': 5}

This is shorthand for d["apples"] = d["apples"] + 1. It assumes the key is present: looking up a missing key in a regular dictionary raises KeyError. See the Python built-in types documentation.

Handle a key that may be missing

For an occasional update to a regular dictionary, use get to supply the starting value, then assign the sum:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
d = {"apples": 4}
key = "oranges"
amount = 1

d[key] = d.get(key, 0) + amount

print(d)  # {'apples': 4, 'oranges': 1}

d.get(key, 0) returns the value for key when it exists, or 0 when it does not. The assignment is what stores the updated result in the dictionary. Choose a different default if zero is not the appropriate starting value for your data.

Choose a pattern for repeated updates

Use defaultdict(int) for ongoing accumulation

When many keys may appear over repeated updates, collections.defaultdict can create a zero count the first time a missing key is accessed with square brackets:

from collections import defaultdict

counts = defaultdict(int)
counts["apple"] += 1
counts["apple"] += 1

print(counts["apple"])  # 2

The factory int returns zero. On a missing-key square-bracket lookup, defaultdict calls that factory, inserts the resulting value, and returns it. This is the pattern shown in the Python collections documentation.

Use Counter when the task is counting occurrences

collections.Counter is designed for counting hashable objects. It can count an iterable initially, and a missing item reads as zero, so incrementing it is straightforward:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from collections import Counter

items = ["apple", "pear", "apple"]
counts = Counter(items)
counts["apple"] += 1

print(counts["apple"])  # 3

A Counter can contain zero or negative counts; reaching zero does not automatically remove an entry. See the Counter reference.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

When to use setdefault

setdefault(key, value) inserts and returns value only when the key is absent; if the key exists, it returns the existing value. It can be used for an increment:

d[key] = d.setdefault(key, 0) + amount

For numeric updates, get plus assignment or defaultdict(int) usually makes the intent clearer. setdefault by itself initializes a missing key; it does not increment an existing value. Its behavior is documented in the Python collections examples.

Common pitfalls

  • Forgetting the assignment: adding an amount to a value does not update the dictionary unless the result is assigned to its key.
  • Assuming a missing regular-dict key starts at zero: d[key] += 1 raises KeyError if the key is absent.
  • Assuming defaultdict.get() creates an entry: its get() method behaves like a normal dictionary’s. It does not call the default factory; d.get(key) returns None when the key is absent unless you supply another default.
  • Using zero when it is not the right default: if values may be None, or should begin from something other than zero, select a default that fits the data.

Which approach should you use?

Situation Use
The key is guaranteed to exist d[key] += amount
The key may be absent, with only occasional updates to a regular dictionary d[key] = d.get(key, 0) + amount
You repeatedly accumulate values under keys that may be absent defaultdict(int)
You are counting occurrences of hashable items Counter

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.