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/

40 Upvotes

15 comments sorted by

View all comments

Show parent comment

2

u/Iron-Man-2008 Aug 29 '26

_ in match case is actually a special wildcard pattern and does not bind to a name.

>>> def foo(seq):
...     match seq:
...         case [1]:
...             print(seq)
...         case [1, *_]:
...             print(_)
...
>>> foo([1])
[1]
>>> foo([1, 2, 3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in foo
NameError: name '_' is not defined
>>>