Get the type of the key of a dictionary

If i understood your question right, the cleanest way i know to get types of all keys in a dict is :

types1 = [type(k) for k in d1.keys()]
types2 = [type(k) for k in d2.keys()]

or if you want to have all the unique types you can use:

types1 = set(type(k) for k in d1.keys())
types2 = set(type(k) for k in d2.keys())

like that you'll know if there is a single or multiple types. (Thanks @Duncan)

this returns lists with types of keys found in respective dicts:

o/p:

[<class 'int'>, <class 'int'>, <class 'int'>]
[<class 'str'>, <class 'str'>, <class 'str'>]

However, if you're asking about the type of d2.keys() it's:

<class 'dict_keys'>

Hope this was somehow helpful.


If you want to find out if your dictionary has only string keys you could simply use:

>>> set(map(type, d1)) == {str}
False

>>> set(map(type, d2)) == {str}
True

The set(map(type, ...)) creates a set that contains the different types of your dictionary keys:

>>> set(map(type, d2))
{str}
>>> set(map(type, d1))
{int}

And {str} is a literal that creates a set containing the type str. The equality check works for sets and gives True if the sets contain exactly the same items and False otherwise.