Reputation: 737
I have a dictionary -
d = dict(
0='a',
1='b',
2='c'
)
How can I tell if d
is a dict
of type (int, str)
?
In C# it'd be something like:
d.GetType() == typeof(Dictionary<int, string>)
Upvotes: 0
Views: 182
Reputation: 16184
if you're using Python 3.7 you can do something like:
from typing import Dict
d: Dict[int, str] = { 0: 'a', 1: 'b', 2: 'c' }
print(__annotations__['d'])
and get back: typing.Dict[int, str]
there's a function typings.get_type_hints
that might be useful in the future, but currently only knows about objects of type:
function, method, module or class
PEP-0526 also says something is to be done about this
Upvotes: 0
Reputation: 8927
Python dictionaries don't have types. You'd literally have to check every key and value pair. E.g.
all(isinstance(x, basestring) and isinstance(y, int) for x, y in d.items())
Upvotes: 2
Reputation: 164683
Within a single Python dictionary, values may be of arbitrary types. Keys have the additional requirement that they must be hashable, but they may also cover multiple types.
To check keys or values in a dictionary are of a specific type, you can iterate them. For example:
values_all_str = all(isinstance(x, str) for x in d.values())
keys_all_int = all(isinstance(x, int) for x in d)
Upvotes: 1