Article
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.
On this page0%
- Part 1 — ModuleNotFoundError
- Cause 1: the package is not installed
- Cause 2: you installed it for a different Python
- Cause 3: the import name differs from the install name
- Cause 4: your own file shadows the package
- Cause 5: importing your own module from the wrong place
- Quick checklist
- Part 2 — KeyError
- Fix 1: use .get() when the key may be missing
- Fix 2: check first
- Fix 3: print the real keys
- KeyError in pandas
- Fix 4: build counters with defaultdict
- The habit that prevents both
- FAQ
- What does ModuleNotFoundError: No module named mean?
- How do I fix ModuleNotFoundError after pip install?
- What is a KeyError in Python?
- How do I stop KeyError without hiding bugs?
- Next reading on Sythra Articles
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:
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.
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:
import sys
print(sys.executable)
Then install using exactly that interpreter:
"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 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.
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:
import os
print(os.getcwd())
Quick checklist
- Spelling and capitalisation of the import
python -m pip show <package>— does it list a location?- Does
sys.executablematch the environment you installed into? - Is any of your files named like the package?
Part 2 — KeyError
KeyError: 'email'
You looked up a dictionary key that is not there:
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
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
if "email" in user:
send(user["email"])
else:
print("No email on file")
Fix 3: print the real keys
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:
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).
A related error, 'NoneType' object is not subscriptable, appears when .get() returns None and you then index it. See that fix.
Fix 4: build counters with defaultdict
A very common reason for KeyError is counting things:
counts = {}
for word in ["a", "b", "a"]:
counts[word] += 1 # KeyError on the first 'a'
Fix it with collections:
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:
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.