Sub topic 5
Handling missing keys and indexes
Nested data often arrives incomplete. A config file may lack a section, an API response may omit a field, and a list may be shorter than you expected. This chapter covers three ways to read such data safely: get(), the in operator, and try/except.
This chapter assumes you can create lists and dictionaries, index into them, and write for loops and simple functions. It also assumes you have seen chained indexing such as data["a"][0]["b"].
Why chained access fails
Each step in a chained lookup can fail on its own. A missing dictionary key raises KeyError. An index past the end of a list raises IndexError. Using the wrong kind of value at a step raises TypeError. An example is indexing into None.
config = {"db": {"host": "localhost"}}
for lookup in (
lambda: config["cache"]["ttl"],
lambda: config["db"]["host"][99],
lambda: config["db"]["host"]["x"],
):
try:
lookup()
except Exception as err:
print(type(err).__name__, err)
# KeyError 'cache'
# IndexError string index out of range
# TypeError string indices must be integers, not 'str'The error message names only the step that failed. It does not tell you how deep you were when it failed.
Option 1: get() with a default
dict.get(key, default) returns the default instead of raising KeyError. If you leave out the default, it returns None.
To go several levels deep, chain get() calls. Use an empty dictionary as the default for each middle step, so the next get() has something to call.
config = {"db": {"host": "localhost"}}
port = config.get("db", {}).get("port", 5432)
print(port) # 5432
ttl = config.get("cache", {}).get("ttl")
print(ttl) # NoneIf you wrote config.get("cache").get("ttl"), the first call would return None. The second call would then fail with AttributeError. The {} default prevents this.
get() works only on dictionaries. Lists have no get() method.
Option 2: the in operator
The in operator checks whether a key exists before you read it. This matters when you must tell "the key is missing" apart from "the key is present with the value None".
settings = {"timeout": None}
print("timeout" in settings) # True
print(settings.get("timeout")) # None
print("retries" in settings) # False
print(settings.get("retries")) # NoneBoth lookups with get() return None, so you cannot tell the cases apart from the result. The in check can.
For lists, you can check an index against the length.
grades = [90, 85]
index = 2
if 0 <= index < len(grades):
print(grades[index])
else:
print("no grade at index", index) # no grade at index 2Note that in on a list tests for a value, not an index. 85 in grades is True, but 1 in grades is False.
Option 3: try and except
Sometimes a missing key means the data is broken, and your code should say so. Wrap the lookup in try and catch the specific exception.
config = {"db": {"host": "localhost"}}
try:
print(config["cache"]["ttl"])
except KeyError as err:
print("missing key:", err) # missing key: 'cache'You can catch both error types at once with a tuple. This is useful for paths that mix dictionaries and lists.
data = {"users": [{"name": "Ana"}]}
def first_user_name(data):
try:
return data["users"][0]["name"]
except (KeyError, IndexError):
return None
print(first_user_name(data)) # Ana
print(first_user_name({"users": []})) # None
print(first_user_name({})) # NoneChoosing between them
| Situation | Best tool |
|---|---|
| A missing value has a sensible default | `get()` with a default |
| You must distinguish "absent" from `None` | `in` |
| A missing value is an error you want to report | `try`/`except` |
| The path mixes dictionaries and lists | `try`/`except` with `(KeyError, IndexError)` |
Common mistakes
- Catching bare
except:orexcept Exception:hides unrelated bugs. NameKeyErrorandIndexError. - Using
get(key, [])and then changing the result does not store anything in the dictionary. The default is a fresh object that the dictionary never sees. - Using
get(key) or defaultreplaces valid falsy values such as0or""with the default.
counts = {"errors": 0}
print(counts.get("errors") or 10) # 10, which is wrong
print(counts.get("errors", 10)) # 0, which is correctExercise
Write a function first_grade(students, name) that takes a list of dictionaries like {"name": "Ana", "grades": [90, 85]} and returns the first grade for the student with that name. It should return None if the student is missing, has no grades key, or has an empty grades list.
Show answer
def firstgrade(students, name): for student in students: if student.get("name") == name: grades = student.get("grades", []) return grades[0] if grades else None return None print(firstgrade([{"name": "Ana", "grades": [90, 85]}], "Ana")) # 90 print(firstgrade([{"name": "Ben"}], "Ben")) # None print(firstgrade([], "Cy")) # None
Exercise
Why does counts.get("errors") or 10 return 10 when counts is {"errors": 0}, and how do you fix it?
Show answer
The value 0 is falsy, so or discards it and uses 10. Pass the default to get() instead: counts.get("errors", 10). This returns 0 because the key exists.