Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python match case dictionary keys

Getting the following error when using match case (python 3.10.4). I'm trying to use dictionary keys to make the cases modular.

TypeError: called match pattern must be type

keys = { 'A': 'apple',
         'B' : 'banana'}
fruit = 'A'
match fruit:
    case keys.get('A'):
        print('apple')
   
    case keys.get('B'):
        print('Banana')
like image 782
Gami Avatar asked Mar 21 '26 04:03

Gami


1 Answers

A pattern is not an expression; it's a syntactic contract. You can't call a dict method as part of the pattern. You need to get the value before the match statement. Something like

from types import SimpleNamespace

values = SimpleNamespace(**{v: k for k, v in keys.items()})
match fruit:
    case values.apple:
        print('apple')
    case values.banana:
        print('Banana')

However, there's no particular reason to use a match statement here; a simple if statement would suffice:

if fruit == keys.get('A'):
    print('apple')
elif fruit == keys.get('B'):
    print('Banana')

Syntactically, the match statement is trying to treat keys.get('A') as a class pattern, with keys.get referring to a type and 'A' as a literal argument used to instantiate the type. For example, you could write

x = 6

match x:
    case int(6):
        print("Got six")

where the class pattern int(6) matches the value 6.

like image 189
chepner Avatar answered Mar 22 '26 17:03

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!