FULL PYTHON FIX · 6 MIN READ

How to Fix KeyError for a Missing Python Dictionary Key

A dictionary lookup with square brackets requires the exact key to exist. Inspect the available keys, then decide whether a missing key should be handled or treated as an error.

Before you start: Dictionaries · Conditions

Quick fix

If an absent key is normal, test membership with key in scores before using brackets.

PYTHON
scores = {'Ada': 8}
requested = 'Bo'
if requested in scores:
    print(scores[requested])
else:
    print('No score for', requested)
print('default:', scores.get(requested, 0))
See why this works and test the edge cases

Video guide: How to Fix KeyError for a Missing Python Dictionary Key

The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube

Read the video transcript

Select a timestamp to watch that moment on YouTube.

  1. 00:00

    This program has one score stored under the name Ada. It asks for the score under Bo and stops with KeyError. The message includes the key Bo, which is useful evidence: Python could not find that exact key in this dictionary. A dictionary is not like a list where an integer position points to an item. Its keys are chosen by the program, and a square-bracket lookup requires the requested key to exist. In this video, we will reproduce the failure, inspect the exact stored keys, and choose between three behaviors. We can treat a missing key as an error that should be fixed in the data. We can show a clear message when missing keys are expected.

  2. 00:41

    Or we can use a meaningful default for a particular calculation. These choices are different, and replacing every lookup with a default can hide a real data problem. First, I will run the program unchanged. The dictionary literal creates a valid dictionary. The exception occurs only when the next line requests Bo. Keep that order in mind when reading a traceback: find the specific operation that failed before editing unrelated code. We will begin by checking whether the key was misspelled or truly absent. The stored key is Ada with a capital A, while the requested key is ada with a lowercase a.

  3. 01:21

    Those are different Python strings, so the lookup fails. The membership test says false before we attempt square brackets. A real key mismatch can also come from leading or trailing spaces, a different spelling, or a field name that never arrived in the input data. Repr helps expose invisible spaces when you print the requested value. Before adding a fallback, determine what the data rule should be. If names are supposed to be case-insensitive, normalize them when you store them and when you look them up, using the same rule both times. But do not call lower on one random lookup and assume the data is fixed. Some identifiers are intentionally case-sensitive, and silently merging two names could create a different bug.

  4. 02:07

    If the code expected Bo to exist because another step should have inserted it, the missing key may reveal that earlier step failed. In that case, keeping a KeyError during development can be helpful. The traceback is telling you that an assumption about the data was false. Fix the assumption or handle the missing case deliberately. In an interactive results page, a name might legitimately have no score yet. A membership check makes that possibility explicit. If requested is present, we use square brackets. If it is absent, we display a helpful message. The same code still returns Ada's actual score when the name changes to Ada.

  5. 02:49

    The final line shows another option: dictionary get with a default of zero. That returns zero for Bo without raising an exception. But zero must mean something appropriate for this application. If a missing score means not graded, reporting zero may be misleading. We might choose a different label, a special value, or no lookup at all. Get does not add Bo to the dictionary. It only returns the chosen fallback for this call. That distinction matters when building counts: after reading a default count, assign the incremented count back into the dictionary. We will demonstrate that next. Do not use a default simply because it makes the error disappear.

  6. 03:31

    Decide whether absence is expected, and state what a missing value means to the rest of the program. This test exposes a subtle mistake. Ada is present with a score of zero. Bo is present with a value of None. Cy is absent. A condition like if scores dot get name would treat both zero and None as false, even though those keys exist. Get without an explicit default would also return None for both Bo and Cy, so its result alone cannot distinguish a stored None from a missing key. The membership test preserves all three cases. This is why testing a zero value is useful when you introduce fallback logic.

  7. 04:12

    Now consider a word counter. Start with an empty dictionary. For each word, read counts dot get word comma zero, add one, and assign that number back under the word. The first red begins at zero and becomes one. Blue does the same. The second red reads one and becomes two. The assignment is essential because get does not store anything. Run that code and inspect the final dictionary: red maps to two and blue maps to one. You have now used a default where it has a clear meaning, the previous count when a word has not yet been seen. The output confirms the counting example. We could not get this result by calling get alone; the assignment stores each updated count.

  8. 04:57

    On the website, the practice task starts with an inventory containing pen with zero in stock and pencil with three. Write a function that reports zero in stock for pen but not listed for a missing eraser. Then add one eraser using get with a default count of zero and an assignment. That exercise checks whether you can distinguish a present key holding zero from an absent key. When KeyError appears in your own code, follow a short investigation. Read the exact key in the traceback. Print the dictionary's keys and use repr on the requested key to catch spelling, capitalization, and whitespace differences. Decide whether the key should always be present.

  9. 05:39

    If it should, repair the data or the earlier logic instead of hiding the error. If missing keys are normal, choose a membership check when presence matters, or get when a meaningful default is enough. Finally, test a present value, a missing value, and a present value that is false-like, such as zero or None. Those cases reveal many fragile fixes. The full guide and interactive dictionary lessons are linked below the video, with code you can change for your own examples.

Request a key that the dictionary does not contain

Run the code below. Ada has a score, but Bo does not. The lookup scores['Bo'] raises KeyError. Unlike a list index, a dictionary key is not an automatic position: it must match one of the keys stored in the dictionary. The key shown on the traceback's final line identifies the value Python could not find.

This can happen when a user supplies an unfamiliar name, a CSV row omits a field, or a key has different capitalization than expected. The bracket form is useful when a missing key is genuinely a program error, because it makes the problem visible. First check whether the key is supposed to exist.

Broken lookup
PYTHON
scores = {'Ada': 8}
print(scores['Bo'])
ERROR (LAST LINE)
KeyError: 'Bo'

Inspect the exact keys and the requested value

Print the dictionary's keys and the exact requested value. repr() makes extra spaces visible. The example below asks for 'ada' while the stored key is 'Ada'. Python string keys are case-sensitive, so those are different keys. Leading or trailing spaces are different too. Diagnose whether the data is wrong, the lookup is wrong, or missing values are normal for this task.

Do not immediately call lower() or strip() on one side of the lookup. If normalization is part of the data rule, apply the same documented rule when creating keys and when looking them up. Otherwise you may silently combine names that should remain distinct.

See the exact mismatch
PYTHON
scores = {'Ada': 8}
requested = 'ada'
print('keys:', list(scores))
print('requested:', repr(requested))
print('present:', requested in scores)
OUTPUT
keys: ['Ada']
requested: 'ada'
present: False

Choose a membership check or an explicit fallback

If an absent key is normal, test membership with key in scores before using brackets. This lets you show an explanatory message instead of crashing. For a single lookup with a default value, scores.get(key, default) is shorter. Here a score of zero is a deliberate fallback, not an accident. Choose a fallback that is truthful for your application.

dict.get() does not insert the missing key into the dictionary. If you are counting occurrences, assign the new count back: counts[word] = counts.get(word, 0) + 1. If a missing score means the record is corrupt, keep brackets and repair the source data instead of silently substituting zero.

Handle a missing name explicitly
PYTHON
scores = {'Ada': 8}
requested = 'Bo'
if requested in scores:
    print(scores[requested])
else:
    print('No score for', requested)
print('default:', scores.get(requested, 0))
OUTPUT
No score for Bo
default: 0
Use get() when building counts
PYTHON
counts = {}
for word in ['red', 'blue', 'red']:
    counts[word] = counts.get(word, 0) + 1
print(counts)
OUTPUT
{'red': 2, 'blue': 1}

Test present, absent, and present-with-None keys

Verify both an existing key and a missing one. Also consider whether None can be a real stored value. get(key) returns None both when the key is missing and when the key exists with value None. If those cases mean different things, use a membership check instead of comparing get(key) with None.

The example below shows all three cases. A real score of zero must remain zero; using a truthiness test such as if scores.get(name) would incorrectly treat it as missing. An explicit membership check preserves the difference between an absent key and a present key whose value happens to be zero or None.

Distinguish absent from a stored None
PYTHON
scores = {'Ada': 0, 'Bo': None}
for name in ['Ada', 'Bo', 'Cy']:
    if name in scores:
        print(name, repr(scores[name]))
    else:
        print(name, 'missing')
OUTPUT
Ada 0
Bo None
Cy missing
  • Check exact spelling, capitalization, and whitespace before adding a fallback.
  • Use in when presence matters; get() when a missing key has a meaningful default.
  • Do not mistake a stored zero or None for an absent key.

Practice the fix

Given inventory = {'pen': 0, 'pencil': 3}, write describe_stock(item) that returns 'not listed' for a missing key and '0 in stock' for 'pen'. Test 'pen', 'pencil', and 'eraser'. Then add one 'eraser' with inventory['eraser'] = inventory.get('eraser', 0) + 1.

Need a hint?

Use if item not in inventory to identify absence. A value of zero is present, so do not use if inventory.get(item) as the presence test.

Python console

Ready to run

Edit the code and run it in your browser. Examples above can be loaded with Try this example.

Does your code use input()? Add one value per line
Ctrl / ⌘ + Enter to run
OUTPUT
Your output appears here.

Write your solution, then select Check practice.

    Key takeaways

    • Dictionary brackets raise KeyError when the exact key is absent.
    • Inspect the stored keys and requested key before deciding the correct fix.
    • Use membership when presence matters; use dict.get() when a default is meaningful.
    • A zero or None value can be stored under a present key, so truthiness alone is not a safe presence test.

    What to do next

    1. Review the prerequisite: Dictionaries.
    2. Prove it yourself: Pass the checked task in Dictionaries.
    3. Use it in a project: Handle a missing contact lookup, then run the project source on GitHub .

    Related lessons

    Sources and further reading