Gami
Gami

Reputation: 33

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')

Upvotes: 3

Views: 2535

Answers (1)

chepner
chepner

Reputation: 530960

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.

Upvotes: 2

Related Questions