# KeyError: 'x'

**Code:** `KeyError` · **Category:** Python · **Seen on:** Python

You accessed a dictionary key that doesn’t exist.

## Meaning

`d['key']` raises KeyError when the key is missing. Common with JSON responses, environment variables (`os.environ['X']`) and pandas columns.

## Common causes

- Key absent in API/JSON response
- Environment variable not set
- Typo or different casing
- pandas column name has extra spaces

## Quick fix

1. Use `d.get('key', default)`
2. Check `'key' in d` first
3. For env vars, `os.environ.get('X')` and fail with a clear message
4. pandas: `df.columns = df.columns.str.strip()`

## Detailed fix by platform

### Python

1. Safer access:

```python
token = os.environ.get("API_TOKEN")
if not token:
    raise RuntimeError("API_TOKEN is not set")
name = data.get("user", {}).get("name", "unknown")
```


## Code examples

### dict.get, setdefault and defaultdict

```python
from collections import defaultdict

config = {"host": "localhost"}
port = config.get("port", 5432)                 # no KeyError

counts = defaultdict(int)
for word in words:
    counts[word] += 1                           # missing keys start at 0
```

### pandas column KeyError

```python
print(df.columns.tolist())          # ['Name ', 'Email']  ← note the trailing space
df.columns = df.columns.str.strip()
df["Name"]
```

## How to diagnose

1. **Key** — Which key is missing (printed in the error)?
2. **Data** — Print the dict keys / df.columns at that point
3. **Source** — Did the API/file/env actually provide it?
4. **Default** — Is a default value acceptable, or should it fail loudly?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/python/keyerror)
