Sub topic 6
Matching dictionaries
This chapter assumes you know how match, case, literal patterns, and capture patterns work. It also assumes you can read basic dictionary code. Here you will see how mapping patterns match dictionaries, which is common when you handle JSON-like data.
The shape of a mapping pattern
A mapping pattern is written with curly braces. Each entry has a key and a pattern for its value:
def handle(event):
match event:
case {"type": "click", "pos": (x, y)}:
return f"click at {x},{y}"
case {"type": "key", "key": key, **rest}:
return f"key {key} with {len(rest)} extra fields"
case _:
return "ignored"
print(handle({"type": "click", "pos": (3, 4)})) # click at 3,4
print(handle({"type": "key", "key": "a", "shift": True})) # key a with 1 extra fieldsThe first case succeeds only if the subject is a mapping with a "type" key equal to "click" and a "pos" key holding a two-element sequence. The names x and y are then bound to those two elements.
Rules that differ from sequence patterns
Mapping patterns behave differently from the sequence patterns in the previous chapter.
- Extra keys are allowed. A pattern lists the keys it needs. Other keys in the subject are ignored. Sequence patterns, by contrast, must match the exact length.
- Listed keys must exist. If any key is missing, the case fails.
- Keys must be literals or dotted names. You can write
"type",42, orColor.RED. You cannot write a bare variable as a key. - `rest
collects the leftovers.** It builds a new dictionary of the unmatched items. It must come last, and you cannot write**_`, because ignoring the extras is already the default. - The subject must be a mapping. Any
dictqualifies, as does any other type registered as acollections.abc.Mapping. A list or a string never matches. {}matches any mapping, including a non-empty one. To test for an empty dictionary, use a guard such ascase d if not d:.
Nesting patterns
Value patterns can be any pattern, including other mapping patterns, sequence patterns, and class patterns. This makes it possible to check the shape of a nested response in one line:
def describe(resp):
match resp:
case {"status": "ok", "data": {"items": [first, *_]}}:
return f"first item: {first}"
case {"status": "ok"}:
return "ok, no items"
case {"status": "error", "message": str(msg)}:
return f"error: {msg}"
case _:
return "unrecognized"
print(describe({"status": "ok", "data": {"items": [7, 8]}})) # first item: 7
print(describe({"status": "ok", "data": {"items": []}})) # ok, no items
print(describe({"status": "error", "message": "boom"})) # error: boom
print(describe([1])) # unrecognizedThe second call shows why order matters. The first case fails because [] has no first element. Python then tries the next case, and {"status": "ok"} matches. The pattern str(msg) checks that the message is a string and binds it to msg.
Common errors
- Using a variable as a key.
case {key: value}is a syntax error. Capture the value only, or use a literal key. - Expecting an exact match.
{"type": "click"}also matches{"type": "click", "pos": (1, 2)}. Put the most specific cases first, or use a guard to reject unwanted extra keys. - Putting `rest` before other entries.** It must be the last item.
- Forgetting that a missing key means no match. A pattern requiring
"pos"quietly falls through when"pos"is absent. End with acase _that handles the unexpected input.
Exercise
Write a function kind(msg) that returns "login" for any mapping with "action": "login" and a "user" key, "logout" for any mapping with "action": "logout", and "bad" for everything else. What does kind({"action": "login", "user": "ana", "ip": "1.2.3.4"}) return, and why?
Show answer
Use match msg: with case {"action": "login", "user": _}: return "login", case {"action": "logout"}: return "logout", and case _: return "bad". The call returns "login" because mapping patterns ignore extra keys, so "ip" does not stop the first case from matching.