LookupError in Python
LookupError in Python in Python means python could not find something you asked for by name or key. LookupError is the parent of KeyError and IndexError, and it appears on its own for unknown text encodings, missing NLTK data, and context variables with no value.
How do I fix LookupError in Python?
LookupError in Python means a lookup by name or key found nothing. It is the parent class of KeyError and IndexError. A plain LookupError usually means an unknown encoding name, such as .encode("utf8x"), or NLTK data that was never downloaded. Fix the name, for example "utf-8", or run nltk.download() with the resource the message names.
- 1. Read the full messageThe text after LookupError names what was missing: an encoding, an NLTK resource, or a key.
- 2. Check encoding namesUse a standard name such as "utf-8" or "latin-1" in open(), .encode() and .decode().
- 3. Catch narrowlyexcept LookupError also catches KeyError and IndexError. Catch the specific one so real bugs stay visible.
What does LookupError in Python mean?
LookupError means "I looked it up and it is not there". Most of the time you see one of its children: KeyError (missing dictionary key) or IndexError (position past the end). You see a plain LookupError when a library looks something up by name, like an encoding name in .encode() or open(), or a data package in NLTK.
Why does LookupError in Python happen?
1. A misspelled or unsupported encoding name
Encoding names must be ones Python knows. "utf8x" or "utf_8x" are typos; "utf-8" is what you almost always want.
Breaks
data = "héllo".encode("utf8x")
# LookupError: unknown encoding: utf8xWorks
data = "héllo".encode("utf-8")2. NLTK data that was never downloaded
NLTK ships its word lists and models separately. Its error message names the exact resource to download.
Breaks
import nltk
nltk.word_tokenize("Hello there")
# LookupError: Resource punkt not found.Works
import nltk
nltk.download("punkt") # once; newer NLTK may ask for "punkt_tab"
nltk.word_tokenize("Hello there")3. Catching LookupError hides a KeyError or IndexError
Because KeyError and IndexError both inherit from LookupError, except LookupError catches both. That can hide a bug you meant to see.
Breaks
try:
price = prices[item][0]
except LookupError:
price = 0 # also hides a wrong indexWorks
price_list = prices.get(item)
price = price_list[0] if price_list else 0How to find it in your own code
Read the full message after LookupError: it usually names what was missing (an encoding, a resource, a key). Check the spelling first, then whether that thing was ever installed, downloaded or added.
Practise type errors
None of the challenges raises this exact error yet. These practise the same kind of bug.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.