← Python lessons

Python Dictionary get(): Defaults and Counting Items

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

A dictionary's get() method reads a key's value or returns a default when the key is missing. Use it to build counts from an empty dictionary.

Read Dictionaries and For loops first. This lesson uses get() to count repeated categories without a separate missing-key check.

Run each example on its own with the Run button. Each block supplies its own fixed data and needs no imports or helper functions.

Read with a default

Write get(key, default) when a missing key should have a fallback value.

counts = {"win": 2}
print(counts.get("win", 0))
print(counts.get("loss", 0))

This prints 2, then 0. Unlike counts["loss"], the second lookup does not raise KeyError.

A default does not add a key

get() only reads. Assign a value when you want to store it.

counts = {}
print(counts.get("win", 0))
print(counts)
counts["win"] = counts.get("win", 0) + 1
print(counts)

This prints 0, {}, then {'win': 1}. The assignment creates the entry, not the call to get().

Count repeated values

Start with {}. For each result, read its previous count, add 1, and store the new count.

outcomes = {}
for result in ["win", "loss", "win"]:
    outcomes[result] = outcomes.get(result, 0) + 1
print(outcomes)

This prints {'win': 2, 'loss': 1}. A new key starts from 0; an existing key keeps its count. Updating a count does not move its key, so "win" stays first. An empty input list leaves {}.

A stored None is not a missing key

The default applies only when the key is absent. Without an explicit default, get() returns None for a missing key.

counts = {"win": None}
print(counts.get("win", 0))
print(counts.get("loss"))
print("win" in counts)
print("loss" in counts)

This prints None, None, True, then False. Adding 1 to None raises TypeError, so keep counts numeric. Use in when you need to distinguish a missing key from a stored None.

Note: The counting example uses ready-made category strings. Counting words also needs rules for capitals and punctuation; this example leaves that cleaning out.

See also: The accumulator pattern, String methods.

Your turn

Count each word in words using get() and a loop. Print the counts, then read the missing word "plum" with a default of 0 and print the result.

words = ["pear", "apple", "pear", "apple", "pear"]
counts = {}
# add a counting loop, then print counts and the default lookup for plum

Expected output

{'pear': 3, 'apple': 2}
0