'Structural pattern matching on dictionaries using `**`

Is there a reasoning for this?

dct = {'a': 1, 'b': 2}
dct_1 = {'a': 1}
dct_2 = {'b': 2}
match dct:
  case {'b': 2, **dct_1}: print("using {'b': 2, **dct_1}", dct)

outputs,

using {'b': 2, **dct_1} {'a': 1, 'b': 2}

but,

match dct:
  case {**dct_1, 'b': 2}: print("using {**dct_1, 'b': 2}", dct)

gives error,

    case {**dct_1, 'b': 2}: print("using {**dct_1, 'b': 2}", dct)
                   ^^^
SyntaxError: invalid syntax

and,

match dct:
  case {**dct_1, **dct_2}: print("using {**dct_1, **dct_2))}", dct)

gives error,

    case {**dct_1, **dct_2}: print("using {**dct_1, **dct_2))}", dct)
                   ^^
SyntaxError: invalid syntax


Solution 1:[1]

This is just how the syntax for mapping patterns is defined.

At most one double star pattern may be in a mapping pattern. The double star pattern must be the last subpattern in the mapping pattern.

If there were multiple double-star patterns, it would be ambiguous which items should match which patterns. I suspect it's just too much trouble to decide which items a non-final double-star pattern should match without matching the explicit patterns first, so it is just disallowed. Note that a mapping pattern is not an expression, so there isn't a strong need to support as much flexibility as a dict display supports.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 martineau