Fix "KeyError" in Python (dict, pandas, os.environ)
KeyError: 'name'
- KeyError: 'DATABASE_URL'
- KeyError: 0
- KeyError: "None of [Index(['Name'], dtype='object')] are in the [columns]"
- KeyError: "['price'] not in index"
You are reading d["name"] while the key "name" does not exist in the dict, the pandas DataFrame or os.environ. Print the available keys to spot the difference (case, space, type), then use d.get("name", default) or check "name" in d when the key may be missing.
What this error means
Bracket access obj[key] on a dict, a DataFrame or os.environ requires the key to exist. When it is missing, Python does not return None: it raises KeyError with the representation of the requested key, for example KeyError: 'name' or KeyError: 0. That representation is valuable, because it shows the exact spaces, case and type. Pandas also raises KeyError when a column or index label does not exist, with a longer message listing the missing labels.
Common causes
- Key really missing: an API response or JSON that does not always contain the field, or an error response with a different structure.
- Slightly different name: case (
'Name'instead of'name'), trailing space ('name '), BOM at the start of a CSV ('\ufeffname'). - CSV read with the wrong separator: a
;-separated file read with the default comma yields a single column namedname;age;city. - Wrong key type: JSON keys are always strings, so
data[1]fails whiledata["1"]works. In pandas,df.loc[0]looks up label0, which may be gone after filtering. - Environment variable not set:
os.environ["DATABASE_URL"]while the variable is not exported or the.envfile is not loaded.
Step-by-step fix
-
Compare the requested key with the available keys
The traceback shows the key with
repr(). Print the real keys next to it: a case, space or type difference becomes obvious. For a JSON response, paste it into a JSON validator to see its structure.print(repr(key)) print(list(data.keys())) # dict print(df.columns.tolist()) # pandas DataFrame -
Use get() or in when the key may be missing
dict.get()returns a default value instead of raising. If the key is mandatory, catchKeyErrorand raise a clearer error.name = user.get("name", "anonymous") if "email" in user: send_welcome(user["email"]) try: price = prices[sku] except KeyError: raise ValueError(f"unknown SKU: {sku!r}") from None -
Initialize counters and groupings
When counting or grouping,
d[k] += 1fails on a new key.collections.Counter,defaultdictorsetdefaultcreate the key automatically.from collections import Counter, defaultdict counts = Counter(words) groups = defaultdict(list) for order in orders: groups[order["customer_id"]].append(order) -
Clean up pandas columns
Read the CSV with the right separator and the
utf-8-sigencoding (which strips the BOM), then normalize column names. To access a row by position rather than by label, useiloc.import pandas as pd df = pd.read_csv("clients.csv", sep=";", encoding="utf-8-sig") df.columns = df.columns.str.strip().str.lower() print(df.columns.tolist()) names = df["name"] if "name" in df.columns else pd.Series(dtype=str) first_row = df.iloc[0] # by position, not by label -
Handle environment variables
Read optional variables with
os.environ.get()oros.getenv(), and give an explicit message for required ones. If they live in a.envfile, load it withpython-dotenvbefore reading them.import os from dotenv import load_dotenv # pip install python-dotenv load_dotenv() debug = os.getenv("DEBUG", "false") == "true" db_url = os.environ.get("DATABASE_URL") if db_url is None: raise RuntimeError("DATABASE_URL is not set: add it to .env or export it") -
Check the key type
After
json.loads, every key is a string. Convert the key before access, or rebuild the dict with integer keys.import json data = json.loads('{"1": "alice", "2": "bob"}') user = data[str(user_id)] by_id = {int(k): v for k, v in data.items()} user = by_id[user_id]
Did this fix work for you?
Confirm it in one click: it will rise for the next developers stuck on the same error.
Keep it from coming back
- Validate external data (API, JSON, CSV) as soon as it arrives with a schema, for example a Pydantic model, rather than accessing keys throughout the code.
- Use constants or a
TypedDictfor key names so that a typo is caught bymypyorpyright. - Check required environment variables when the application starts, not when they are first used.
Frequently asked questions
How do I remove a key without a KeyError?
Use d.pop("key", None): the default value avoids the error when the key does not exist. For a set, s.discard(x) replaces s.remove(x).
Should I prefer get() or try/except KeyError?
get() fits when absence is normal and a default value makes sense. try/except is better when the key should exist and its absence must be reported.
Why a KeyError on a pandas column that is clearly displayed?
The real name often contains a space, a capital letter or an invisible BOM. Print df.columns.tolist() to see the exact names, then clean them with str.strip().
Useful tools for this error
More Python errors
- Fix "ModuleNotFoundError: No module named" in Python
- Fix "IndentationError: unexpected indent" in Python
- Fix "'NoneType' object is not subscriptable" in Python
- Fix "error: externally-managed-environment" with pip
- Fix "UnicodeDecodeError: 'utf-8' codec can't decode byte" in Python
- Fix "RecursionError: maximum recursion depth exceeded" in Python
- Fix "attempted relative import with no known parent package" in Python