---
title: "Fix ModuleNotFoundError and KeyError in Python"
description: "Two errors every beginner hits. Learn what ModuleNotFoundError and KeyError actually mean, the exact causes, and the fast fix and habit for each."
url: https://articles.sythra.ai/articles/fix-modulenotfounderror-keyerror-python
slug: fix-modulenotfounderror-keyerror-python
author: "vaibhavkothari"
author_url: https://articles.sythra.ai/writers/vaibhavkothari
date_published: 2026-11-12T21:11:00.153Z
date_modified: 2026-11-12T21:11:00.153Z
topics: ["Python", "Debugging", "Errors"]
reading_time_minutes: 5
publisher: "Sythra"
publisher_url: https://sythra.ai
access: free
language: en
---

# Fix ModuleNotFoundError and KeyError in Python

> Two errors every beginner hits. Learn what ModuleNotFoundError and KeyError actually mean, the exact causes, and the fast fix and habit for each.

Source: https://articles.sythra.ai/articles/fix-modulenotfounderror-keyerror-python · Author: vaibhavkothari · Published: 2026-11-12 · Reading time: 5 min · Topics: Python, Debugging, Errors

Two of the most common Python errors look unrelated, but both say the same thing: *"you asked for a name I cannot find."* One is about packages, the other about dictionary keys. Here is how to read each message and fix it in minutes.

## Part 1 — ModuleNotFoundError

```
ModuleNotFoundError: No module named 'requests'
```

Python ran `import requests`, searched every folder it knows, and found nothing with that name. There are only a handful of real causes.

### Cause 1: the package is not installed

The most common one. Install it:

```bash
python -m pip install requests
```

Use `python -m pip`, not bare `pip`. That guarantees the package goes into the **same Python** that runs your script. If `pip` itself is not recognised, see [the Windows pip fix](https://articles.sythra.ai/articles/pip-not-recognized-windows-fix).

### Cause 2: you installed it for a different Python

You can have several Pythons on one machine: the system one, one per virtual environment, one inside VS Code, one in Anaconda. Installing into one does nothing for the others.

Find out which Python is actually running your code:

```python
import sys
print(sys.executable)
```

Then install using exactly that interpreter:

```bash
"C:\path\printed\above\python.exe" -m pip install requests
```

In VS Code, choose the interpreter with **Ctrl+Shift+P → Python: Select Interpreter**, and make sure it matches the environment where you installed the package. [Virtual environments](https://articles.sythra.ai/articles/venv-vs-conda-vs-uv) exist to make this predictable.

### Cause 3: the import name differs from the install name

Some packages install under one name and import under another:

| Install with | Import with |
|---|---|
| `opencv-python` | `import cv2` |
| `scikit-learn` | `import sklearn` |
| `pillow` | `from PIL import Image` |
| `beautifulsoup4` | `from bs4 import BeautifulSoup` |
| `pyyaml` | `import yaml` |

Typing `pip install cv2` fails or installs the wrong thing. For this exact case read [No module named cv2](https://articles.sythra.ai/articles/no-module-named-cv2-fix).

### Cause 4: your own file shadows the package

If you name your script `requests.py` or `random.py`, Python imports *your file* instead of the real library. It often fails with a confusing error about missing attributes. Rename your file, and delete the leftover `__pycache__` folder beside it.

### Cause 5: importing your own module from the wrong place

```
ModuleNotFoundError: No module named 'helpers'
```

`helpers.py` must sit in the same folder as the script you run, or inside a package. Check the working directory:

```python
import os
print(os.getcwd())
```

### Quick checklist

1. Spelling and capitalisation of the import
2. `python -m pip show <package>` — does it list a location?
3. Does `sys.executable` match the environment you installed into?
4. Is any of your files named like the package?

## Part 2 — KeyError

```
KeyError: 'email'
```

You looked up a dictionary key that is not there:

```python
user = {"name": "Ada", "age": 36}
print(user["email"])   # KeyError: 'email'
```

The text after `KeyError:` is the missing key. Read it character by character; the cause is often a typo, extra space or different capitalisation.

### Fix 1: use `.get()` when the key may be missing

```python
email = user.get("email")            # None if missing
email = user.get("email", "unknown") # your own default
```

Use this when absence is normal. Do **not** use it to hide bugs where the key *must* exist; a loud `KeyError` is better than a silent `None` flowing through your program.

### Fix 2: check first

```python
if "email" in user:
    send(user["email"])
else:
    print("No email on file")
```

### Fix 3: print the real keys

```python
print(user.keys())
print(list(user))
```

Seeing the real keys settles most cases. Typical surprises:

- `"Email"` vs `"email"`
- `"first name"` vs `"first_name"`
- A trailing space: `"email "`
- The key is the integer `1`, but you looked up the string `"1"`

### KeyError in pandas

```
KeyError: 'Price'
```

For DataFrames the cause is nearly always a column name that differs from what you typed, especially from CSV files that have stray spaces or a hidden character at the start. Check:

```python
print(df.columns.tolist())
df.columns = df.columns.str.strip()   # remove stray spaces
```

If a column "disappeared" after a `groupby`, it became the index; use `reset_index()` (see [groupby and merge explained](https://articles.sythra.ai/articles/pandas-groupby-merge-explained)).

A related error, `'NoneType' object is not subscriptable`, appears when `.get()` returns `None` and you then index it. See [that fix](https://articles.sythra.ai/articles/nonetype-not-subscriptable-fix).

### Fix 4: build counters with `defaultdict`

A very common reason for `KeyError` is counting things:

```python
counts = {}
for word in ["a", "b", "a"]:
    counts[word] += 1      # KeyError on the first 'a'
```

Fix it with `collections`:

```python
from collections import Counter, defaultdict

counts = Counter(["a", "b", "a"])
print(counts)             # Counter({'a': 2, 'b': 1})

groups = defaultdict(list)
for name, team in [("Ada", "x"), ("Grace", "y"), ("Linus", "x")]:
    groups[team].append(name)
print(dict(groups))       # {'x': ['Ada', 'Linus'], 'y': ['Grace']}
```

## The habit that prevents both

Both errors are really a mismatch between what you *think* exists and what *does*. Before debugging deeper, print the facts:

```python
import sys
print(sys.executable)        # which Python?
print(sorted(data.keys()))   # which keys?
```

A thirty-second print beats ten minutes of guessing.

## FAQ

### What does ModuleNotFoundError: No module named mean?

Python could not find a package or file with that import name in any folder it searches. Usually the package is not installed in the Python interpreter running your script.

### How do I fix ModuleNotFoundError after pip install?

You probably installed into a different Python. Run `python -m pip install <package>` with the same interpreter that runs your script, and confirm it with `sys.executable`.

### What is a KeyError in Python?

A KeyError means you requested a dictionary key that does not exist. The message shows the missing key. Check spelling and capitalisation, or use `dict.get()` if the key is optional.

### How do I stop KeyError without hiding bugs?

Use `.get()` only for keys that are genuinely optional. For required keys, let the error appear so the bug is visible at its source.

## Next reading on Sythra Articles

- ['NoneType' object is not subscriptable — fix](https://articles.sythra.ai/articles/nonetype-not-subscriptable-fix)
- [Virtualenv vs conda vs uv](https://articles.sythra.ai/articles/venv-vs-conda-vs-uv)
- ['pip' is not recognized — fix it on Windows](https://articles.sythra.ai/articles/pip-not-recognized-windows-fix)
