• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Python match case dictionary keys

Resolved: Python match case dictionary keys

0
By Isaac Tonny on 16/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

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

Answer:

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.

If you have better answer, please add a comment about this, thank you!

python python-3.10
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Is pandas groupby() function always produce a DataFrame with the same order respect to the column we group by?

24/03/2023

Resolved: Kivy widget hierarchy not behaving as expected

24/03/2023

Resolved: Pandas Groupby Get Values from Previous Group

24/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.