Get the types of the keys in a dictionary Get the types of the keys in a dictionary python-3.x python-3.x

Get the types of the keys in 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.


d1.keys() returns <class 'dict_keys'> type objects which is iterable but you can not index it like lists

>>> d1 = { 1:'one', 2:'two', 5:'five' }>>> d1.keys<built-in method keys of dict object at 0x7f59bc897288>>>> d1.keys()dict_keys([1, 2, 5])>>> type(d1.keys())<class 'dict_keys'>>>> [i for i in d1.keys()][1, 2, 5]>>> [i for i in d1.keys() if isinstance(i, int)][1, 2, 5]

Also just repeating what you said

>>> d1.keys()[0]Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: 'dict_keys' object does not support indexing

Also Check this out