Check if the type of a variable is dict[str, Any] in Python

I want to check if the type of a variable is: dict[str, Any]. (in python)

What I have tried (unsuccessfully) is this:

myvar = {
 'att1' : 'some value',
 'att2' : 1
}


if not isinstance(myvar, dict[str, Any]):
  raise Exception('Input has the wrong type')

I get the following error message:

TypeError: isinstance() argument 2 cannot be a parameterized generic

How should I do this?

Thank you!

Answer

Try the below – make sure you have a dict and the keys of the dict are strings.

data1 = {
    'att1': 'some value',
    'att2': 1
}

data2 = {
    'att1': 'some value',
    13: 1
}


def check_if_dict_with_str_keys(data):
    return isinstance(data, dict) and all(isinstance(x, str) for x in data.keys())


print(check_if_dict_with_str_keys(data1))
print(check_if_dict_with_str_keys(data2))

output

True
False