Sub topic 3
Reading values: [], get() and in
This chapter assumes you can create a dictionary, know that keys must be hashable, and are comfortable with try/except. It covers the three ways to read from a dictionary and when to use each.
Indexing with []
Square brackets look up a key and return its value. If the key is missing, Python raises a KeyError.
user = {"name": "Ada", "role": "admin"}
print(user["name"]) # Ada
try:
user["email"]
except KeyError:
print("no email key")A KeyError is often what you want. If a missing key means your data is wrong, failing loudly is better than carrying on with a made-up value.
Reading safely with get()
The get() method returns a default instead of raising. Without a second argument, the default is None.
user = {"name": "Ada", "role": "admin"}
print(user.get("email")) # None
print(user.get("email", "n/a")) # n/aget() never changes the dictionary. It also cannot tell you whether the key was absent or was present with the value None:
profile = {"nickname": None}
print(profile.get("nickname")) # None
print(profile.get("age")) # NoneBoth calls print None, although only the second key is missing. When that difference matters, test for the key first or use a unique default object.
MISSING = object()
profile = {"nickname": None}
value = profile.get("nickname", MISSING)
print(value is MISSING) # False: the key exists
value = profile.get("age", MISSING)
print(value is MISSING) # True: the key is absentTesting for keys with in
The in operator checks keys only, never values. It returns True or False and does not read the value.
user = {"name": "Ada", "role": "admin"}
print("role" in user) # True
print("Ada" in user) # False: "Ada" is a value, not a key
print("email" not in user) # TrueTo search values, use "Ada" in user.values(). That scans every value, so it is slower than a key check.
Choosing between them
The diagram shows how to pick.
| Tool | Key missing | Returns | Typical use |
|---|---|---|---|
| `d[key]` | Raises `KeyError` | The value | Required data |
| `d.get(key, default)` | Returns the default | The value or default | Optional data |
| `key in d` | Gives `False` | A boolean | Branching on presence |
Common errors
Writing if d[key]: to check whether a key exists raises KeyError when it is absent. It also treats falsy values such as 0 or "" as missing. Use if key in d: for presence, or d.get(key) when a falsy value really should count as "no value".
Another mistake is checking and then reading, like this:
stock = {"apple": 3}
if "apple" in stock:
count = stock["apple"]
else:
count = 0This works, but it looks the key up twice. count = stock.get("apple", 0) does the same job in one step. Use the check-then-read form only when the two branches do different things.
The default in get() is evaluated eagerly, even when the key exists. d.get(k, expensive()) calls expensive() every time. For costly defaults, use an if k in d branch instead.
Finally, get() does not insert the default. After stock.get("pear", 0), "pear" is still not in stock. Chapter material on setdefault() and defaultdict covers reading and inserting together.
Exercise
Given config = {"debug": False, "retries": 0}, what do config.get("debug", True), config.get("retries") or 3 and "timeout" in config evaluate to, and why is the second one risky?
Show answer
The first returns False, because the key exists and its value is used, not the default. The second returns 3, because 0 is falsy, so or replaces a valid value of zero retries. The third returns False, because "timeout" is not a key. To keep a stored 0, write config.get("retries", 3), which only uses the default when the key is absent.