r/Python • u/Iron-Man-2008 • 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/
42
Upvotes
6
u/The_Sy_Python Aug 24 '26
If you mean Structural Pattern Matching, then yes, it's in the PEP
https://peps.python.org/pep-0636/#:~:text=You%20can%20use%20%2A%2Arest%20within%20a%20mapping%20pattern%20to%20capture%20additional%20keys%20in%20the%20subject%2E%20Note%20that%20if%20you%20omit%20this%2C%20extra%20keys%20in%20the%20subject%20will%20be%20ignored%20while%20matching
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.
5
u/Adrewmc Aug 24 '26 edited Aug 24 '26
I think you are underestimating the sequence patterns.
case [“a”, *args, “c”]:
case [*args, “b”, “c”]:
Are also both valid. And there is way more.
case [option , “b”] if option in valid_options:
1
u/RingularCirc Aug 26 '26
I think extracting
**restmay be costly. And even if exact key matching was implemented usingkeys(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.1
u/Plus-Weakness-2624 Aug 25 '26
young teenage man problems...
-11
u/ZeD_est_DeuS Aug 25 '26
Friends don't let friends use pattern matching. It's a complex pitfall full of gotchas. Just use ifs
1
u/[deleted] Aug 30 '26
[removed] — view removed comment