Sub topic 5
Handling Missing Keys and Indexes
What this chapter assumes
You should already be comfortable with these points from earlier chapters:
- Reading nested data with chained indexing, such as
data["users"][0]["name"]. - Basic
try/exceptsyntax. - What
dict.get()does at a single level.
This chapter covers what happens when a step in a chain points at something that does not exist. It also covers the ways to handle that case, and how to choose between them.
Three errors, three causes
A chained lookup runs one step at a time. Each step can fail in its own way, and the error type tells you which step went wrong.
config = {"db": {"host": "localhost"}, "servers": ["a", "b"], "cache": None}
attempts = [
lambda: config["db"]["port"],
lambda: config["servers"][5],
lambda: config["cache"]["ttl"],
lambda: config["db"]["host"]["name"],
]
for attempt in attempts:
try:
attempt()
except (KeyError, IndexError, TypeError) as err:
print(type(err).__name__, "-", err)
# KeyError - 'port'
# IndexError - list index out of range
# TypeError - 'NoneType' object is not subscriptable
# TypeError - string indices must be integers, not 'str'| Error | Cause | Example |
|---|---|---|
| `KeyError` | The dictionary has no such key. | `config["db"]["port"]` |
| `IndexError` | The list is too short for that position. | `config["servers"][5]` |
| `TypeError` | The value at that step is not the container you assumed. | `None["ttl"]`, or a string indexed with a string |
TypeError is the one that surprises people. A key can exist and still hold None, a number, or a string. Indexing that value then fails at the next step.
The traceback names only the failing operation. It does not say which level of a long chain broke, so the safe-access techniques below are also easier to debug.
Choosing a strategy
There are two styles. Look before you leap (LBYL) tests whether the access will work first. Easier to ask forgiveness than permission (EAFP) tries the access and handles the failure.
The sections below cover each branch.
Testing with the in operator
For dictionaries, in checks keys at one level. Chain the tests with and, which stops at the first false test:
config = {"db": {"host": "localhost"}}
if "db" in config and "port" in config["db"]:
print(config["db"]["port"])
else:
print("no port configured")
# no port configuredUse in when you need to do something different depending on whether the key is there. An example is logging a warning, or creating the entry.
Lists need more care. in on a list checks the values, not the positions:
servers = ["a", "b"]
print("a" in servers) # True: "a" is a value
print(0 in servers) # False: 0 is not a value, even though index 0 existsTo test a position, compare it against the length. Negative indexes are valid down to -len(servers):
index = 5
print(-len(servers) <= index < len(servers)) # FalseUsing get() with a default
dict.get(key, default) returns the default instead of raising KeyError. Chaining it with an empty dictionary as the default keeps the chain going:
config = {"db": {"host": "localhost"}}
port = config.get("db", {}).get("port", 5432)
print(port) # 5432
timeout = config.get("cache", {}).get("ttl", 60)
print(timeout) # 60If "cache" is missing, get returns {}. The second get then runs on an empty dictionary and returns the final default.
The None trap
The chained form fails if a key exists but holds None. The default only applies when the key is absent:
config = {"db": None}
try:
config.get("db", {}).get("port", 5432)
except AttributeError as err:
print(err) # 'NoneType' object has no attribute 'get'This often happens with data from JSON or a database, where null is common. One fix is or {}, which replaces any falsy value:
port = (config.get("db") or {}).get("port", 5432)
print(port) # 5432or replaces every falsy value, not just None. That includes 0, "", and []. This is fine when you expect a container, as above. It is wrong for a final value such as a retry count where 0 is meaningful:
settings = {"retries": 0}
print(settings.get("retries") or 3) # 3, which is wrong: 0 was a real value
print(settings.get("retries", 3)) # 0Telling "missing" from "set to None"
get(key) returns None both for an absent key and for a key whose value is None. When the difference matters, use a sentinel. A sentinel is a unique object that no real data can equal:
MISSING = object()
settings = {"proxy": None}
for key in ("proxy", "timeout"):
value = settings.get(key, MISSING)
if value is MISSING:
print(key, "is not set")
else:
print(key, "is set to", value)
# proxy is set to None
# timeout is not setHandling errors with try/except
When a missing value means the data is wrong, let the access fail and catch it in one place. This avoids testing every level, and it reports the problem instead of hiding it behind a default.
config = {"db": {"host": "localhost"}}
try:
ttl = config["cache"]["ttl"]
except KeyError as err:
print("missing key:", err) # missing key: 'cache'Keep these habits:
- Catch the narrowest exception that fits. A bare
except:also hides typing mistakes andKeyboardInterrupt. - Keep the
trybody small. If it contains ten lines, aKeyErrorfrom line seven looks the same as one from line two. - The exception message contains only the key that failed, here
'cache'. If you want to report more, add context yourself, for exampleraise ValueError("config needs a cache section") from err.
Missing indexes
IndexError works the same way. A small helper keeps the call sites readable:
def safe_index(items, index, default=None):
try:
return items[index]
except IndexError:
return default
servers = ["a", "b"]
print(safe_index(servers, 1)) # b
print(safe_index(servers, 5)) # None
print(safe_index(servers, -3, "none")) # noneFor the first item of a possibly empty list, next(iter(items), default) is a short alternative:
print(next(iter([]), "empty")) # empty
print(next(iter([7, 8]), "empty")) # 7Slices never raise. servers[5:] returns [], which can be handy, but it also hides the fact that the position was out of range.
One helper for mixed paths
Chains that mix keys and indexes, such as data["users"][0]["emails"][0], are awkward with get() because lists have no equivalent. A small function walks a path of steps and returns a default on any failure:
def dig(data, *path, default=None):
current = data
for step in path:
try:
current = current[step]
except (KeyError, IndexError, TypeError):
return default
return current
data = {"users": [{"name": "Ana", "emails": ["[email protected]"]}]}
print(dig(data, "users", 0, "emails", 0)) # [email protected]
print(dig(data, "users", 1, "name")) # None
print(dig(data, "users", 0, "phone", default="n/a")) # n/a
print(dig(data, "users", 0, "name", "first")) # NoneThe last call shows why TypeError is in the list. "Ana"["first"] raises TypeError, so the helper returns the default instead of crashing.
The helper has two limits:
- It collapses every failure into the same default. You cannot tell a missing key from a wrong type, so use it for optional data only.
- Strings accept integer indexes.
dig(data, "users", 0, "name", 0)returns"A"without any error. If a step might land on a string, check the type.
Reads that create entries
Some tools change the data when you read it. defaultdict is the main example:
from collections import defaultdict
counts = defaultdict(list)
_ = counts["x"] # a read, but it inserts the key
print("x" in counts) # True
print(dict(counts)) # {'x': []}A lookup on a defaultdict never raises KeyError, and it also grows the dictionary. A typo in a key then creates a new entry instead of an error. Use defaultdict while building data, and consider converting to a plain dict with dict(counts) before you hand the data to other code.
The write-side tool for plain dictionaries is setdefault(). It returns the existing value, or inserts and returns the default:
config = {}
config.setdefault("cache", {})["ttl"] = 60
config.setdefault("cache", {})["size"] = 10
print(config) # {'cache': {'ttl': 60, 'size': 10}}The next chapters on building nested structures cover both tools in more depth.
Comparing the approaches
| Approach | Best for | Weakness |
|---|---|---|
| `in` test | Reacting differently to present and absent keys | Verbose on deep chains. On lists it checks values, not positions. |
| `get()` with default | Optional keys where a default is sensible | Fails with `AttributeError` if an intermediate value is `None`. |
| `get()` with a sentinel | Telling "absent" from "set to None" | Needs a shared `MISSING` object. |
| `try`/`except` | Required data, reporting errors, mixed key and index paths | Too broad a `try` body hides the real failure. |
| `dig()` helper | Many optional lookups in mixed structures | Hides which step failed. |
Common mistakes
- Using a default to silence a real bug.
get("usre", {})with a typo returns an empty result and the program carries on. Use defaults only for keys that are allowed to be absent. - Forgetting that
get()only handles absence. A key holdingNonepasses straight through the default. - Using
orwith legitimate falsy values.0,"",False, and empty containers are all replaced. - Catching
Exception. This hides errors unrelated to the lookup. - Not checking types on external data. Data from JSON or an API can have a list where you expected a dictionary. Check with
isinstance(value, dict)before you trust the shape, or catchTypeErroralong withKeyError.
Exercises
Exercise
What happens when you run {"db": None}.get("db", {}).get("port", 5432), and how would you change the expression so that it returns 5432?
Show answer
It raises AttributeError: 'NoneType' object has no attribute 'get'. The key "db" exists, so get() returns its value None and ignores the {} default. Replace the first lookup with (data.get("db") or {}), as in ({"db": None}.get("db") or {}).get("port", 5432), which returns 5432.
Exercise
Given order = {"items": [{"sku": "A1", "tags": ["new"]}]}, use the dig() helper from this chapter to read the first tag of the second item, and return "none" if it does not exist. Then say which error type the helper handled.
Show answer
dig(order, "items", 1, "tags", 0, default="none") returns "none". The list "items" has only one element, so order["items"][1] raises IndexError, which dig() catches and answers with the default.