Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A Python KeyError means code tried to retrieve a mapping value with a key that is not present. In person["age"], square brackets require "age" to exist; person.get("age") does not. The right fix depends on what the missing key means: provide a valid fallback for optional data, validate or repair malformed input, or let the exception expose a broken required-data contract.

What a KeyError means

Python raises KeyError when a mapping lookup cannot find the requested key. It is a subclass of LookupError, alongside IndexError (Python exception hierarchy).

user = {"name": "Ada"}
print(user["email"])
# KeyError: 'email'

The exception displays the missing key, which can be a string, integer, tuple, or another hashable object:

scores = {1: 100}
scores[2]
# KeyError: 2

This behavior is defined at the mapping level, so custom mapping classes and library objects can raise KeyError too.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

How to read the traceback

profile = {"name": "Ada"}
print(profile["email"])
Traceback (most recent call last):
  ...
KeyError: 'email'
  • The traceback points to the source line where the failure surfaced.
  • The final line gives the exception type and associated key.
  • The key shown may be a computed value, not the field name you expected.
  • The lookup may be inside a helper, loop, comprehension, callback, or library function.

Python’s tutorial explains how exceptions propagate outward until a compatible handler is found (Errors and exceptions).

Choose a response based on what absence means

Situation Approach Reason
Key is mandatory data[key] Fail loudly and expose invalid state
Key is optional data.get(key, default) Make the fallback explicit
Presence changes control flow if key in data Handle present and absent cases differently
One lookup has a recoverable failure path try/except KeyError Attempt the operation once, then recover
Repeated grouping or counting defaultdict Encode automatic initialization
One-time default-container insertion setdefault() Compact, but mutates the mapping
Optional removal pop(key, default) Avoid an exception for normal absence

Use .get() for optional keys

For an optional field, get() expresses the intended fallback without raising:

user = {"name": "Ada"}
email = user.get("email")
print(email)  # None

label = user.get("email", "Not provided")

The default is used only when the key is absent. An existing None remains None:

data = {"count": None}
print(data.get("count", 0))  # None

If missing and explicit None have different meanings, use a sentinel:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
_MISSING = object()
value = data.get("status", _MISSING)

if value is _MISSING:
    print("status is absent")
elif value is None:
    print("status is explicitly null")

get() is not validation. A fallback such as None, an empty string, or zero must be valid for the operation that follows. See the dictionary get() documentation.

Test membership when presence drives the decision

if "email" in user:
    send_email(user["email"])
else:
    request_email_address()

Use this form when the present and absent branches do materially different things. For a simple fallback, a single get() call is clearer than checking and then looking up:

email = user.get("email")

A membership test followed by a lookup is also not universally safe for shared mutable data: another thread or process could change the mapping between the two operations. Synchronize access when required.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Catch KeyError narrowly

try/except is useful when the lookup itself is the operation you are attempting:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
person = {"name": "Ada"}

try:
    age = person["age"]
except KeyError:
    age = 0

print(age)

Capture the key when it helps diagnostics:

try:
    email = user["email"]
except KeyError as error:
    print(f"Missing required field: {error.args[0]}")
    email = "Not provided"

Keep the protected block small. Otherwise, a KeyError raised by unrelated code can be mistaken for a missing field:

try:
    email = user["email"]
except KeyError:
    email = "Not provided"
else:
    send_email(email)

Python’s tutorial recommends catching intended exception types and using else for code that should run only after a successful try block (official tutorial). Do not replace a narrow handler with except Exception merely to suppress failures.

When direct indexing is the correct fix

Do not eliminate every KeyError. If a function requires a key, direct indexing protects its contract:

def create_invoice(order):
    customer_id = order["customer_id"]
    total = order["total"]
    return {"customer_id": customer_id, "total": total}

Silently substituting None or an empty value could create a corrupt invoice. Handle an expected absence; expose an unexpected absence.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Defaults that mutate mappings

setdefault()

setdefault() returns the existing value or inserts and returns the supplied default when the key is absent:

groups = {}
groups.setdefault("admins", []).append("Ada")
print(groups)
# {'admins': ['Ada']}

It mutates the dictionary, evaluates its default argument before the call, and can hide whether insertion was intentional. It is convenient for a one-off grouping operation:

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
groups = {}
for name, department in records:
    groups.setdefault(department, []).append(name)

For a mapping whose missing keys should consistently create containers, defaultdict is usually clearer (setdefault() reference).

defaultdict

from collections import defaultdict

counts = defaultdict(int)
for word in ["red", "blue", "red"]:
    counts[word] += 1

print(counts)
# defaultdict(<class 'int'>, {'red': 2, 'blue': 1})

For grouping:

groups = defaultdict(list)
for name, department in records:
    groups[department].append(name)

A missing-key access through data[key] calls the factory and inserts the key. Other methods do not necessarily do so:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
data = defaultdict(list)
data["missing"]       # creates the key
data.get("another")    # returns None; does not create it

That read-side mutation can unexpectedly grow the mapping. Use defaultdict only when automatic creation is part of the data model (defaultdict documentation).

Remove optional keys safely

pop() raises KeyError when the key is absent unless a default is supplied:

value = data.pop("temporary", None)

Without that second argument, absence is an error. See the dict.pop() reference.

Nested dictionaries need structure-aware handling

Every lookup in a chain can fail:

city = response["user"]["address"]["city"]

For genuinely optional JSON-like data, a short chain can work:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
city = (response.get("user", {})
                .get("address", {})
                .get("city"))

However, this conflates absence with empty objects and can fail when an intermediate value is None or another type. Validate important structures explicitly:

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
user = response.get("user")
if not isinstance(user, dict):
    raise ValueError("response.user must be an object")

address = user.get("address")
if not isinstance(address, dict):
    raise ValueError("response.user.address must be an object")

city = address.get("city")

For larger applications, use a schema or model-validation layer instead of scattering defensive lookups through business logic.

Fix spelling, whitespace, and key-type mismatches

Exact spelling and invisible characters

data = {"Name": "Ada"}
data["name"]  # KeyError: 'name'

"email", "Email", "email ", and " email" are different keys. Inspect the exact values:

print(repr(requested_key))
print(list(data))

For external text, normalize deliberately:

normalized = {key.strip().lower(): value for key, value in data.items()}

Normalization can create collisions or damage identifiers whose case and whitespace are meaningful.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Different key types

data = {1: "one"}
data["1"]  # KeyError: '1'

JSON object keys and URL parameters commonly arrive as strings, while database identifiers may be integers. Inspect both value and type:

print(key, type(key))
print(data.keys())

Establish a key-type contract rather than converting every key to a string automatically.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Validate external data before lookup

For configuration, API responses, files, environment-derived values, or database records, a missing key may be a contract violation:

required = ("api_url", "api_token")
missing = [key for key in required if key not in config]
if missing:
    raise ValueError(f"Missing configuration keys: {missing}")

Use config.get("timeout", 30) for an optional setting, but config["api_token"] for a required one. Also distinguish a missing key from a present null/None, a wrong type, and an invalid value; KeyError addresses only absence.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Debugging checklist

  1. Read the traceback’s source line and final exception line.
  2. Print repr(requested_key) to reveal whitespace and escapes.
  3. Inspect list(data) or data.keys().
  4. Print the key’s type and compare it with the mapping’s key types.
  5. Check whether an intermediate nested value is None or the wrong type.
  6. At system boundaries, log enough context to identify the record without exposing secrets.
  7. In PyCharm, open Run → View Breakpoints, choose Add → Python Exception Breakpoint, and enable breaking when the exception is raised. The documented shortcut is Ctrl+Shift+F8; labels and keymaps can vary by release and operating system (PyCharm breakpoints).

Custom mappings and intentional errors

A custom mapping may translate keys, load values lazily, normalize input, or raise a different exception. A dict subclass can implement __missing__() for bracket access:

class DefaultsDict(dict):
    def __missing__(self, key):
        return "unknown"

data = DefaultsDict(name="Ada")
print(data["email"])  # unknown

__missing__() is a hook for d[key]; it does not automatically change get() or membership behavior (documentation).

Application or library code can raise KeyError deliberately:

def get_setting(settings, name):
    if name not in settings:
        raise KeyError(name)
    return settings[name]

When adding domain context, preserve the original cause:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
try:
    value = config["database_url"]
except KeyError as error:
    raise RuntimeError("Database configuration is incomplete") from error

Exception chaining retains the original lookup failure while presenting a meaningful higher-level error (exception context and causes).

Recover, propagate, translate, or suppress

Recover

Use a documented fallback, skip a malformed record, or request corrected input when absence is expected.

Report and propagate

import logging
logger = logging.getLogger(__name__)

try:
    process_record(record)
except KeyError:
    logger.exception("Invalid record: missing required field")
    raise

logger.exception() belongs inside the handler so the traceback is included.

Translate

Raise a domain-specific exception with raise NewError(...) from error when callers need business-level context.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Suppress

Suppress only when the absence is explicitly harmless. An empty except KeyError: pass can cause partial writes, incorrect calculations, or corrupted state.

Common mistakes

  • Always using .get(): a fallback can conceal a required-field defect.
  • Catching Exception: this may hide TypeError, AttributeError, and unrelated failures.
  • Catching LookupError indiscriminately: it also catches IndexError; use it only when both recovery paths are genuinely identical.
  • Assuming defaults distinguish missing from None: use a sentinel when those states differ.
  • Forgetting mutation: setdefault() changes the source, and defaultdict[key] creates a key during access.
  • Confusing unhashable keys with missing keys: data[["a"]] raises TypeError, not KeyError.
  • Assuming dictionary views are snapshots: data.keys() is dynamic; call list(data) when a frozen list is needed.

Bottom line

Use square brackets for required keys whose absence should expose invalid state. Use .get() for optional values with a valid fallback, membership tests when presence determines control flow, defaultdict for intentional automatic creation, and a narrow try/except KeyError when recovery naturally follows one lookup. Validate external and nested data early, inspect exact key spelling and types, and never hide unrelated errors behind a broad exception handler.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.