Skip to content
FR
  1. LuzineDebug
  2. Python
  3. KeyError: 'name'
Python Beginner ≈ 5 min to fix

Fix "KeyError" in Python (dict, pandas, os.environ)

Error message
KeyError: 'name'
  • KeyError: 'DATABASE_URL'
  • KeyError: 0
  • KeyError: "None of [Index(['Name'], dtype='object')] are in the [columns]"
  • KeyError: "['price'] not in index"
In short

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.

Be the first to confirm this fix

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

  1. Key really missing: an API response or JSON that does not always contain the field, or an error response with a different structure.
  2. Slightly different name: case ('Name' instead of 'name'), trailing space ('name '), BOM at the start of a CSV ('\ufeffname').
  3. CSV read with the wrong separator: a ;-separated file read with the default comma yields a single column named name;age;city.
  4. Wrong key type: JSON keys are always strings, so data[1] fails while data["1"] works. In pandas, df.loc[0] looks up label 0, which may be gone after filtering.
  5. Environment variable not set: os.environ["DATABASE_URL"] while the variable is not exported or the .env file is not loaded.

Step-by-step fix

  1. 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.

    python
    print(repr(key))
    print(list(data.keys()))      # dict
    print(df.columns.tolist())    # pandas DataFrame
  2. Use get() or in when the key may be missing

    dict.get() returns a default value instead of raising. If the key is mandatory, catch KeyError and raise a clearer error.

    python
    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
  3. Initialize counters and groupings

    When counting or grouping, d[k] += 1 fails on a new key. collections.Counter, defaultdict or setdefault create the key automatically.

    python
    from collections import Counter, defaultdict
    
    counts = Counter(words)
    
    groups = defaultdict(list)
    for order in orders:
        groups[order["customer_id"]].append(order)
  4. Clean up pandas columns

    Read the CSV with the right separator and the utf-8-sig encoding (which strips the BOM), then normalize column names. To access a row by position rather than by label, use iloc.

    python
    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
  5. Handle environment variables

    Read optional variables with os.environ.get() or os.getenv(), and give an explicit message for required ones. If they live in a .env file, load it with python-dotenv before reading them.

    python
    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")
  6. Check the key type

    After json.loads, every key is a string. Convert the key before access, or rebuild the dict with integer keys.

    python
    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 TypedDict for key names so that a typo is caught by mypy or pyright.
  • 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

All Python errors →