Skip to content

KeyError: 'x'

Error message

                'x'
              

Quick summary

You tried to get a value from a dictionary using a key that isn't in the dictionary.

Why this happens

  • Typo in the key name

  • The key was never added to the dictionary

  • The key was deleted or the data source doesn't include it

Minimal example

✗ Broken code
d = {"a": 1}
print(d["b"])
✓ Fixed code
d = {"a": 1}
print(d.get("b", 0))

d["b"] raises KeyError because "b" isn't in the dict — .get("b", 0) returns the default 0 instead.

How to diagnose

  • Print the dictionary keys with dict.keys() to see what's available

  • Check the key spelling against the actual keys

  • Verify the key exists with if key in dict before accessing

How to fix

  • Use dict.get(key) which returns None instead of raising KeyError

  • Use dict.get(key, default) to provide a fallback value

  • Check if key in dict before accessing with dict[key]

How to prevent

  • Use .get() instead of [] when the key might not exist

  • Use defaultdict from collections for dictionaries with default values

Related Resources

Related Lessons

  • Data Types

    Learn about Python dictionaries and data types

Related Practice

← Back to language