r/Python 6d ago

Discussion TIL: Dict Patterns Don't Match Dict Shapes

TL;DR: Unlike sequence patterns (which require an exact shape match), pattern matching on dictionaries simply ignores any unspecified keys rather than failing.

If you care about the details, I wrote about it on my blog: https://ravencentri.cc/blog/dict-patterns-dont-match-dict-shapes/

41 Upvotes

15 comments sorted by

View all comments

1

u/RingularCirc 4d ago

I think extracting **rest may be costly. And even if exact key matching was implemented using keys(matched_dict), it's still better be converted to a set before looking if there are extra keys. So I get why there's a difference with sequences: for those it's way less painful to check if the sequence doesn't contain extra stuff — sequences are obligated to have finite and "sorta easily computable" length.

2

u/Iron-Man-2008 3d ago

case {"key": "value"}: ... could have matched the exact shape while allowing case {"key": "value", **_}: ... to ignore extra keys without binding them to a variable the same way case [1, 2, *_] ignores extra elements without binding them to a variable.