In python, you can't easily enforce keys type and values type for your dict.
This means python has no means to verify all the keys and all the values from your statement:
match some_dict:
case {str(): bool()}: # -> This is invalid
do_something()
You could consider doing some kind of switch case with
TypedDict, however, you can't use anystring keys with this type, you are force to define each of your keys which can often be unwanted.
Nevertheless here are 2 ways you could attack your problem:
PYTHON 3.8 with jsonschema
from contextlib import suppress
from jsonschema import ValidationError, validate
# Watch out, use json types here
# We use anystring regex for property
anystring_bool_dict = {"type": "object", "patternProperties": {"^.*$": {"type": "boolean"}}}
anystring_int_dict = {"type": "object", "patternProperties": {"^.*$": {"type": "integer"}}}
def switch_on_dict_types(case: dict):
with suppress(ValidationError):
if not validate(instance=case, schema=anystring_bool_dict):
print("FIRST_CASE")
with suppress(ValidationError):
if not validate(instance=case, schema=anystring_int_dict):
print("SECOND_CASE")
switch_on_dict_types({"lalal": True})
switch_on_dict_types({"lalal": 1})
# On Execution:
# FIRST_CASE
# SECOND_CASE
Feel free to improve indentation level and complexity from this solution if you manage to do so.
PYTHON 3.10 iterate dict keys, values and using type to string
This ain't perfect, I am just moving your loop but at least you don't run the loop for each case:
def switch_on_dict_types(dict):
for k, v in dict.items():
match str(type(k)) + str(type(v)):
case "<class 'str'><class 'bool'>":
print("string bool case")
case "<class 'str'><class 'int'>":
print("string int case")
switch_on_dict_types({"lalal": True})
switch_on_dict_types({"lalal": 2})
# On Execution:
# string bool case
# string int case