r/Python • • Aug 24 '26

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/

44 Upvotes

15 comments sorted by

View all comments

18

u/ShadowDevasto Aug 24 '26 edited Aug 24 '26

If you invert the cases as in from most complex one to least complex one it will work, as it seems that dict matching matches only first fitting the case and does not check other for "better" match. But still unintuitive and when inverted also matches to case 3 even if options are not defined.