Mapping Pattern Matching (Dictionaries)
1Concept
Mapping patterns match dictionary keys and bind values. Unlike sequence patterns, mapping patterns perform partial matching: the dict can contain extra keys not specified in the case pattern.
2Architecture Diagram
case {"type": "alert", "level": "CRITICAL", **rest}: ---> Matches even if payload has 10 other keys!3Code Example
Python 3.12
def inspect_event(event: dict):
match event:
case {"type": "LOGIN", "status": "FAILED", "ip": ip}:
return f"SECURITY ALERT: Failed login from {ip}"
case {"type": "LOGIN", "status": "SUCCESS", "user": user}:
return f"User logged in: {user}"
case _:
return "Standard event"
print(inspect_event({"type": "LOGIN", "status": "FAILED", "ip": "192.168.1.55", "time": 1709420000}))
print(inspect_event({"type": "LOGIN", "status": "SUCCESS", "user": "alice"}))4Expected Output
SECURITY ALERT: Failed login from 192.168.1.55 User logged in: alice
5Key Takeaways
- ✓Mapping patterns match if the specified keys exist, ignoring unmentioned keys.
- ✓Use `**rest` to capture unmentioned key-value pairs into a dictionary.
- ✓Keys must be literals or attribute lookups (`Enum.KEY`).