KeyError — what it means and how to fix it

A KeyError is a dictionary lookup that missed: the code asked for data["name"] and the dictionary has no key "name". The key in the message is printed in quotes, so KeyError: ‘name’ tells you exactly which key failed. The fix is always about reconciling what the code expects with what the dictionary actually holds.

The fix, in order

  1. Print the actual keys just before the failing line: print(data.keys()). Nine times out of ten the expected key differs in case ("Name"), spelling, or is nested one level deeper than assumed (data["user"]["name"]).
  2. Check where the dictionary came from. JSON from an API changes shape: fields get renamed, wrapped in a "results" list, or omitted when empty. Print the raw structure once before trusting your mental picture of it.
  3. Use .get() when a missing key is legitimate: data.get("name") returns None instead of raising; data.get("name", "Unknown") supplies a default. Reserve hard [] lookups for keys that must exist.
  4. Watch for type mismatches: the key 1 and the key "1" are different keys. Data loaded from JSON or CSV often has string keys where your code uses ints, or the reverse.
  5. For pandas, the same error on a DataFrame means the column name differs — print df.columns.tolist() and compare exactly, including stray spaces some CSVs carry.

If it still happens

If the key exists in your printout but the error persists, you’re probably looking at two different dictionaries — a copy made earlier, before the key was added. Print the full object at the failing line to see the one the code actually has.

Common questions

What’s the difference between KeyError and IndexError? Same idea, different container: KeyError is a missing dictionary key; IndexError is a list position that doesn’t exist.

Should I wrap lookups in try/except KeyError? When absence is an expected case (user input, optional API fields), .get() with a default is cleaner. try/except fits when the whole block should be skipped on a miss.

Related errors

TypeError: 'NoneType' object is not subscriptable · AttributeError: 'NoneType' has no attribute · NameError: name is not defined