Sub topic 3
Reading values: [], get() and in
This chapter assumes you know basic Python syntax, the core built-in types (str, int, list, tuple), for loops and conditionals, and the difference between mutable and immutable objects. It also assumes you can create a dictionary and know that keys must be hashable, as covered in the earlier chapters.
Reading from a dictionary looks simple, but the choice between [], get() and in decides how your code behaves when data is missing. This chapter covers the working model of each tool, when to use it, and the errors that come up most often.
The three ways to read
Python gives you three basic ways to ask a dictionary about a key:
| Tool | Returns | If the key is missing |
|---|---|---|
| `d[key]` | The value | Raises `KeyError` |
| `d.get(key)` | The value | Returns `None` |
| `d.get(key, default)` | The value | Returns `default` |
| `key in d` | `True` or `False` | Returns `False` |
All of them find the key by hashing it, so each takes roughly constant time on average, regardless of how large the dictionary is. The difference is in what they do when the key is absent.
user = {"name": "Ada", "role": "admin"}
print(user["name"]) # Ada
print(user.get("email")) # None
print(user.get("email", "n/a")) # n/a
print("role" in user) # True
try:
user["email"]
except KeyError:
print("no email key")Indexing with []
d[key] is the strict form. It returns the value for the key, or raises KeyError if the key is not there. The exception carries the missing key as its argument.
config = {"host": "localhost", "port": 8080}
try:
config["timeout"]
except KeyError as exc:
print(repr(exc)) # KeyError('timeout')
print(exc.args[0]) # timeoutUse [] when a missing key means a bug or invalid input. In that case you want the program to fail loudly at the point of the mistake, not carry on with a made-up value. For example, a function that requires a "host" setting should index it directly. A KeyError naming host is a clearer error than a connection failure several calls later.
Keys must still be hashable when reading
Lookup hashes the key you pass, so an unhashable key raises TypeError, not KeyError. This applies to [], get() and in alike.
d = {(1, 2): "A"}
print(d[(1, 2)]) # A
try:
d[[1, 2]]
except TypeError as exc:
print(exc) # unhashable type: 'list'This is a common source of confusion. A KeyError means "I could hash that, but it is not in the dictionary". A TypeError means "I could not even hash it".
Reading with get()
d.get(key, default=None) never raises KeyError. If the key exists, it returns the stored value. Otherwise it returns the default, which is None if you do not supply one.
settings = {"theme": "dark"}
print(settings.get("theme")) # dark
print(settings.get("font")) # None
print(settings.get("font", 12)) # 12
print(settings) # {'theme': 'dark'}The last line matters: get() does not insert anything. The dictionary is unchanged. Later in this tutorial you will meet setdefault() and defaultdict, which do insert.
Use get() when a missing key is a normal, expected case, such as optional configuration, optional fields in parsed data, or a counter that may not exist yet.
counts = {}
for ch in "hello":
counts[ch] = counts.get(ch, 0) + 1
print(counts) # {'h': 1, 'e': 1, 'l': 2, 'o': 1}The default is evaluated eagerly
The default argument is an ordinary expression. Python evaluates it before calling get(), even when the key is present. That is harmless for a literal, but wasteful or wrong if the default is expensive or has side effects.
def load_default():
print("loading default...")
return "fallback"
cache = {"key": "cached"}
value = cache.get("key", load_default())
print(value) # prints "loading default..." first, then: cachedIf computing the default is costly, check with in or use a conditional expression, so the work happens only when needed:
value = cache["key"] if "key" in cache else load_default()Testing membership with in
key in d answers whether a key is present and returns a bool. It tests keys only, never values.
stock = {"apple": 3, "pear": 0}
print("apple" in stock) # True
print("kiwi" in stock) # False
print("kiwi" not in stock) # True
print(3 in stock) # False, 3 is a value, not a keyTo test values, use the values() view. Be aware that this scans the values one by one, so it takes time proportional to the size of the dictionary, unlike a key test.
print(3 in stock.values()) # True, but a linear scankey in d and key in d.keys() give the same answer. The shorter form is preferred and avoids creating a view object.
Choosing between them
The decision usually comes down to what a missing key means.
A short rule of thumb:
- Use
d[key]when the key must exist. - Use
d.get(key, default)when a fallback value is fine. - Use
key in dwhen you need to do different things depending on presence, or when you only care about presence.
Common errors and gotchas
Check-then-read is redundant
A frequent pattern checks membership and then indexes, which hashes the key twice:
if "email" in user:
email = user["email"]
else:
email = "n/a"When all you want is a default, user.get("email", "n/a") says the same thing in one line. Keep the two-step form when the branches do different work, not merely a different value.
None is ambiguous
get(key) returns None for a missing key, but None can also be a real stored value. You cannot tell the two cases apart from the return value alone.
profile = {"nickname": None}
print(profile.get("nickname")) # None, key present with value None
print(profile.get("age")) # None, key absent
print("nickname" in profile) # True
print("age" in profile) # FalseIf None is a legitimate value in your data, either use in to test presence, or use a private sentinel object as the default:
MISSING = object()
value = profile.get("nickname", MISSING)
if value is MISSING:
print("key absent")
else:
print("key present:", value) # key present: NoneFalsy values are not missing
Writing if d.get(key): treats 0, "", [] and None the same way as an absent key. A stock level of 0 is a real value, not a missing one.
stock = {"apple": 3, "pear": 0}
if stock.get("pear"):
print("pear in stock")
else:
print("no pears") # prints this, but the key exists
if "pear" in stock:
print("pear is tracked") # prints thisDecide whether you mean "present" or "truthy", and write that explicitly.
Wrong key type
Keys are matched by equality and hash, so 1, 1.0 and True collide, while "1" is a different key altogether.
d = {1: "one"}
print(d.get(1.0)) # one, because 1 == 1.0 and their hashes match
print(d.get(True)) # one, because True == 1
print(d.get("1")) # None, a string is a different keyWhen a lookup returns None unexpectedly, print repr() of the key and of the dictionary's keys. A stray space, a different case, or a string versus an integer is usually the cause.
Nested lookups
Chained indexing fails at the first missing level. Chained get() calls need a default of {} on every level except the last, or the second call will try to call get on None.
data = {"user": {"address": {"city": "Oslo"}}}
print(data["user"]["address"]["city"]) # Oslo
print(data.get("user", {}).get("address", {}).get("city")) # Oslo
print(data.get("account", {}).get("address", {}).get("city")) # NoneWithout the {} defaults, the third line would raise AttributeError: 'NoneType' object has no attribute 'get'. Note that this pattern also fails if an intermediate value exists but is not a dictionary, for example a string. For deeply nested or untrusted data, a small helper function or a try/except KeyError around the whole chain is clearer.
try:
city = data["account"]["address"]["city"]
except KeyError:
city = "unknown"
print(city) # unknownReading while mutating
get() and [] are reads only. They do not add, change or remove entries. Writing is the subject of the next chapter, but one point belongs here: in followed by assignment has a gap between the check and the write. In ordinary single-threaded code this is fine. In multithreaded code another thread could add the key in between, so shared dictionaries need a lock or a different design.
Summary of behavior
d[key]raisesKeyErrorfor a missing key andTypeErrorfor an unhashable one.d.get(key, default)returns the default for a missing key, evaluates the default eagerly, and does not modifyd.key in dtests keys only and is a constant-time operation on average.None,0and""are valid stored values, so test presence within(or a sentinel) when it matters.
Exercise
Given inventory = {"bolts": 0, "nuts": None}, what do inventory.get("bolts"), inventory.get("nuts") and inventory.get("screws") return? Which expression would you use to tell the second case from the third, and why?
Show answer
They return 0, None and None. The second and third calls give the same result, so the return value cannot distinguish a stored None from a missing key. Use "nuts" in inventory (True) versus "screws" in inventory (False), or call get() with a sentinel default such as object() and compare with is.
Exercise
This function should return the port from a settings dictionary, defaulting to 8080 when the key is missing. It runs a slow lookup_port_from_network() call each time. What is wrong, and how do you fix it?
def getport(settings):
return settings.get("port", lookupportfromnetwork())
Show answer
The default argument is evaluated before get() runs, so the slow network call happens even when "port" is present. Fix it by evaluating the default only when needed: return settings["port"] if "port" in settings else lookup_port_from_network(). If the fallback is the constant 8080, settings.get("port", 8080) is fine because a literal costs nothing.
Exercise
Write a short snippet that reads data["order"]["customer"]["email"] from a possibly incomplete nested dictionary and sets email to "unknown" if any level is missing. Why is a try/except KeyError a reasonable choice here?
Show answer
try:
email = data["order"]["customer"]["email"]
except KeyError:
email = "unknown"
A single try covers a missing key at any level, avoids repeating {} defaults on each chained get(), and catches only KeyError, so unrelated bugs still surface. Keep the try body to this one line so no other KeyError is hidden.