Sub topic 6
Matching dictionaries
This chapter assumes you know how match and case blocks run, and that you have seen capture patterns, the _ wildcard, and sequence patterns. You should be comfortable with dictionaries and with ** unpacking.
Dictionaries are the usual shape of decoded JSON, parsed configuration, and event payloads. A mapping pattern lets you test that shape and pull out values in one case line.
The basic shape
A mapping pattern looks like a dictionary display. Each entry pairs a key with a pattern for its value.
def describe(msg):
match msg:
case {"type": "ping"}:
return "pong"
case {"type": "greet", "name": str() as name}:
return f"hello {name}"
case {"type": "greet"}:
return "hello stranger"
case _:
return "unknown"
print(describe({"type": "ping", "id": 7})) # pong
print(describe({"type": "greet", "name": "Ada"})) # hello Ada
print(describe({"type": "greet", "name": 3})) # hello stranger
print(describe({})) # unknownA mapping pattern succeeds when all of these hold:
- The subject is a mapping.
- Every key in the pattern exists in the subject.
- The value for each key matches its sub-pattern.
The first call shows the most important difference from sequence patterns. The subject has an extra "id" key, and the match still succeeds. Mapping patterns never check that the subject has only the listed keys.
The third call shows that a failing value pattern moves on to the next case. "name": 3 is not a str, so the second case fails and the third one catches the message.
Keys are fixed, values are patterns
The two sides of each entry follow different rules.
- A key must be a literal (a string, number, bytes,
True,False, orNone) or a dotted name such asField.NAME. A bare name is a syntax error, because a capture would have to guess which key to look up. - A value can be any pattern: a literal, a capture,
_, an or-pattern, a nested sequence, mapping, or class pattern, or an as-pattern. - Repeating a key in one pattern is a syntax error.
from enum import Enum
class Field(Enum):
NAME = "name"
AGE = "age"
def read(row):
match row:
case {Field.NAME: n, Field.AGE: int() as a}:
return f"{n} is {a}"
case _:
return "bad row"
print(read({Field.NAME: "Lin", Field.AGE: 41})) # Lin is 41
print(read({"name": "Lin", "age": 41})) # bad rowThe keys here are the enum members themselves, not their string values. The second call fails for that reason.
Collecting the rest with `**rest`
Because extra keys are ignored by default, you need **rest when you want to keep them. It must be the last item in the pattern, and it binds a new dict of the entries not named earlier.
def route(request):
match request:
case {"method": "GET", "path": path, **opts}:
return f"read {path} with {len(opts)} options"
case {"method": "POST", "body": {"user": {"id": int() as uid}}}:
return f"create for user {uid}"
case {"method": "POST"}:
return "bad post"
case _:
return "unsupported"
print(route({"method": "GET", "path": "/a", "page": 2, "sort": "asc"}))
# read /a with 2 options
print(route({"method": "POST", "body": {"user": {"id": 9, "name": "x"}}}))
# create for user 9
print(route({"method": "POST", "body": {}}))
# bad postThe second case shows nesting. The inner mapping patterns apply the same rules, so "name": "x" is ignored. If any level is missing or has the wrong type, the whole case fails.
**_ is not allowed. You do not need it, because ignoring extra keys is already the default.
Requiring an exact set of keys
Since extras are allowed, a strict check needs a guard. Capture the rest and require it to be empty.
def strict_point(d):
match d:
case {"x": int() as x, "y": int() as y, **rest} if not rest:
return (x, y)
case _:
return None
print(strict_point({"x": 1, "y": 2})) # (1, 2)
print(strict_point({"x": 1, "y": 2, "z": 3})) # NoneWhat counts as a mapping
The subject does not have to be a dict. It must be an instance of collections.abc.Mapping, which includes dict and its subclasses, ChainMap, and any class that subclasses Mapping. Strings, lists, and other sequences never match a mapping pattern, even when they support indexing.
from collections import ChainMap
settings = ChainMap({"mode": "fast"}, {"mode": "slow", "level": 2})
match settings:
case {"mode": m, "level": lvl}:
print(m, lvl) # fast 2An empty pattern {} matches any mapping, including an empty one. Use it only when you want "is a mapping" with no other condition. Put it after the more specific cases.
Lookup uses `get`, not indexing
Python looks up each key with the mapping's get method. It does not use d[key]. This has a practical consequence: matching a defaultdict does not call __missing__, so it does not insert keys.
from collections import defaultdict
d = defaultdict(list)
match d:
case {"a": _}:
print("has a")
case _:
print("no a")
print(dict(d)) # {}The output is no a followed by {}. A failed match leaves the defaultdict unchanged. If you wrote d["a"] in an if test instead, you would create the key as a side effect.
Value patterns inside entries
Literal values in entries compare with ==, with one exception. True, False, and None compare by identity.
def flag(d):
match d:
case {"ok": True}:
return "yes"
case {"ok": None}:
return "unset"
case _:
return "other"
print(flag({"ok": True})) # yes
print(flag({"ok": 1})) # other
print(flag({"ok": None})) # unset1 == True is True in Python, but {"ok": 1} does not match {"ok": True}, because the pattern uses is. If a payload might carry 1 or "true" for a flag, normalize it before matching.
How a mapping pattern is checked
The diagram shows the order of the checks. A failure at any step makes the whole case fail and sends Python to the next case.
Pitfalls
Several mistakes come up often with mapping patterns.
| Mistake | What happens | Fix |
|---|---|---|
| `case {key: v}` with a bare name | `SyntaxError`, since keys must be literals or dotted names | Use a literal key, or loop over the items with `if` |
| Putting `{"type": "greet"}` before `{"type": "greet", "name": str()}` | The specific case is never reached, because the general one matches first | Order cases from most specific to least |
| Expecting an exact key set | Extra keys are silently accepted | Capture `**rest` and add `if not rest` |
| Matching a JSON string | A `str` is not a mapping, so nothing matches | Call `json.loads` first |
| Using `**_` | `SyntaxError` | Omit it |
| Relying on a name captured in a failed case | Bindings from a partly matched pattern may remain set | Use captured names only inside the case that matched |
Wrong ordering is the hardest to spot, because nothing raises an error. The program just takes the wrong branch. When two cases share the same keys, the one with more constraints must come first.
When mapping patterns fit
Mapping patterns work well for tagged messages, where one field such as "type" selects a variant and the other fields depend on it. They also work well for validating nested JSON, where one pattern replaces several isinstance and in checks.
They fit poorly when the keys are not known ahead of time, because keys cannot be captured. They also fit poorly when you only test one key. In that case d.get("type") == "ping" is shorter and just as clear.
Exercise
Given the code below, what does check({"kind": "a", "n": 5, "extra": 1}) return, and what changes if you add if not rest as a guard on the first case after capturing **rest?
def check(d):
match d:
case {"kind": "a", "n": int() as n}:
return n
case _:
return -1
Show answer
It returns 5, because extra keys are ignored. With the capture **rest and the guard if not rest, the first case fails, since rest is {"extra": 1}. The function then returns -1 from the wildcard case.
Exercise
Write a function area(shape) that uses mapping patterns on dictionaries like {"shape": "rect", "w": 2, "h": 3} and {"shape": "circle", "r": 1}. Return w * h for rectangles and 3.14159 * r * r for circles. Return None for anything else, including a rectangle missing "h".
Show answer
def area(shape): match shape: case {"shape": "rect", "w": w, "h": h}: return w h case {"shape": "circle", "r": r}: return 3.14159 r * r case : return None A rectangle without "h" fails the first case, because every pattern key must be present. It also fails the second case, so it falls through to `` and returns None.