Search code examples
pythondictionarytypesisinstance

How to tell if a variable is a specific type of dictionary? i.e. dict(int, str)


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

Solution

  • 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())