Get the types of the keys in a dictionary
08:40 11 Jul 2017

Is there a "clean" way to take the type of the keys of a dictionary in python3?

For example, I want to decide if one of these dictionaries has keys of type str:

d1 = {1: 'one', 2: 'two', 5: 'five'}
d2 = {'1': 'one', '2': 'two', '5': 'five'}

There are several ways to achieve this, for example, using something like:

isinstance(list(d2.keys())[0], type('str'))

But this is quite annoying because d2.keys() is not indexable, so you need to convert it into a list just to extract the value of one element of the list and check the type.

So does python3 have something like get_key_type(d2)? If not, is there a better (cleaner) way to ask if the key of a dictionary is of type str?

python python-3.x dictionary types