Concepts / Dictionaries: Mapping Keys to Values

Dictionaries: Mapping Keys to Values

The get() method safely retrieves dictionary values, returning a default if the key is missing.

  • Programming

A Safer Dictionary Lookup

A dictionary connects keys with values. When a program needs the value associated with a key, the get() method provides a safe lookup pattern: it retrieves the dictionary value when the key is present and supplies a default value when the key is missing. This makes get() especially useful when a program is counting items and cannot assume that every key has already been added.

Existing and Missing Keys

The get() method has two important cases. If the requested key exists, get() retrieves the value associated with that key. If the key is missing, get() returns the default supplied as its second argument. In the counting idiom, that default is 0 because a key that has not been counted yet has a current count of zero for the purpose of the calculation.

scoreskey-value mappingredkey exists7stored valuebluekey missing0default valuelookupget returnslookupget returns
What does get() return when the key exists, and what does it return when the key is missing?
python
Output
7
0

The Default-Value Path

The second argument to get() is the fallback value. The lookup first considers the requested key. An existing key leads to its associated dictionary value. A missing key leads to the supplied default instead. This is why get() is safer than relying on bracket notation when a key may not exist: the lookup has an explicit result for the missing-key case.

Requested keyKey exists?Stored valueDefault valuelookupyesno
How does a dictionary lookup decide between a stored value and a default?
Best practice

Choose a default that represents the starting value your operation needs. For frequency counting, use 0 because the first occurrence should increase a missing count from zero to one.

From Conditional Logic to Counting

A counting loop must handle two situations: the item may already have a count, or it may be appearing for the first time. An explicit if-statement can separate those cases. The get() idiom combines them by retrieving the current count when available, using 0 otherwise, adding 1, and assigning the result back to the dictionary.

if-statementcheck, then updateupdated countget() idiomretrieve, add, assignupdated countproducesproduces
How does the concise get() expression replace an explicit key-exists branch while preserving the count update?
Before
counts = {}
for item in items:
    if item in counts:
        counts[item] = counts[item] + 1
    else:
        counts[item] = 1

The loop handles an existing key and a missing key in separate branches.

After
counts = {}
for item in items:
    counts[item] = counts.get(item, 0) + 1

The loop uses 0 as the missing-key count, adds 1, and assigns the updated count.

Code walkthrough
items = ["cat", "dog", "cat", "bird"]
counts = {}

for item in items:
    counts[item] = counts.get(item, 0) + 1

print(counts)
  1. 1
    On the first cat, counts.get("cat", 0) supplies 0, so cat receives a count of 1.
  2. 2
    On dog, the key is missing, so dog receives a count of 1.
  3. 3
    On the second cat, get() retrieves the stored count of 1, so cat becomes 2.
  4. 4
    On bird, the key is missing, so bird receives a count of 1.
  • items supplies the values to count.
  • counts starts as an empty dictionary.
  • get(item, 0) retrieves the current count or supplies 0 for a new item.
  • Adding 1 records the current occurrence.
  • The assignment stores the new count under the item key.
Output
{"cat": 2, "dog": 1, "bird": 1}

Building a Frequency Histogram

A histogram records how often each item occurs. A dictionary is a natural structure for this task: each distinct item serves as a key, and its associated value is the number of occurrences counted so far. The get() idiom makes every loop iteration follow the same update rule, whether the item has appeared before or is appearing for the first time.

{}countscat: 1cat encountereddog: 1dog encounteredcat: 2cat encountered againbird: 1bird encounteredcatdogcatbird
How does each item update its corresponding frequency in the histogram?
Worked example

Counting Letter Occurrences

Build a frequency count for the letters in the sequence ["a", "b", "a", "c", "b", "a"].

  1. 1
    Initialize

    Start with an empty dictionary named counts.

  2. 2
    Process a

    The key a is missing, so get("a", 0) returns 0. Add 1 and store a count of 1.

  3. 3
    Process b

    The key b is missing, so get("b", 0) returns 0. Add 1 and store a count of 1.

  4. 4
    Process a again

    The key a exists with a count of 1. Add 1 and store a count of 2.

  5. 5
    Process c

    The key c is missing, so its count becomes 1.

  6. 6
    Process b again

    The key b exists with a count of 1. Add 1 and store a count of 2.

  7. 7
    Process a a third time

    The key a exists with a count of 2. Add 1 and store a count of 3.

Result

The resulting histogram is {"a": 3, "b": 2, "c": 1}.

python
Output
{"a": 3, "b": 2, "c": 1}

Mistakes Beginners Make

  • Common mistake

    Using a lookup pattern that does not provide a missing-key fallback.

    What it looks like

    The counting loop assumes that every item already has a count.

    Why it fails

    A counting loop must handle items that have not appeared before.

    Do this instead

    Use counts.get(item, 0) so a missing item begins with a count of zero.

  • Common mistake

    Forgetting to add one before assigning the result.

    What it looks like
    counts[item] = counts.get(item, 0)
    Why it fails

    The expression retrieves the current count or default but does not record the new occurrence.

    Do this instead
    Use counts[item] = counts.get(item, 0) + 1.
  • Common mistake

    Treating the default as the final count.

    What it looks like

    A missing key receives the default 0 during the lookup.

    Why it fails

    For frequency counting, the current occurrence still needs to be added.

    Do this instead

    Use the default as the starting count, then add 1.

  • Common mistake

    Using get() without considering what the default should mean.

    What it looks like

    A frequency count uses a default other than zero without a counting reason.

    Why it fails

    The default represents the starting value for a missing key.

    Do this instead

    For occurrence counts, use 0 as the default.

Practice the Refactoring

EASY

Rewrite this counting loop using the get() idiom. Then state what the final dictionary contains.

items = ["x", "y", "x", "x", "y"]
counts = {}
for item in items:
    if item in counts:
        counts[item] = counts[item] + 1
    else:
        counts[item] = 1
Hints
  • Keep counts[item] on the left side of the assignment.
  • Use counts.get(item, 0) to retrieve the existing count or starting value.
  • Add 1 before assigning the result.

What do you think happens?

Before checking the answer, predict the final value of counts after processing ["x", "y", "x", "x", "y"] with counts[item] = counts.get(item, 0) + 1.

  • {"x": 3, "y": 2}

  • {"x": 2, "y": 3}

  • {"x": 5, "y": 5}

Reveal answer
Answer:

{"x": 3, "y": 2}

The sequence contains three occurrences of x and two occurrences of y. Each iteration retrieves the current count or uses zero, then adds one.

Working Rule

  1. 1
    get() retrieves the value for an existing dictionary key.
  2. 2
    When the key is missing, get() returns the supplied default value.
  3. 3
    The expression d[c] = d.get(c, 0) + 1 is a concise counting idiom.
  4. 4
    A dictionary histogram maps each distinct item to its frequency.
  5. 5
    Use get() when a key may not exist and the operation needs a defined fallback.

Key Takeaways

  • The get() method safely retrieves a dictionary value or returns a chosen default when the key is missing.
  • For counting, get(c, 0) supplies the starting count for a new key.
  • The idiom d[c] = d.get(c, 0) + 1 replaces verbose conditional counting logic.
  • Repeatedly applying this pattern builds histograms and frequency counts.

Related concepts

More concepts starting with D