Get the types of the keys in a dictionary

Viewed 37513

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 this dictionaries has keys of type str:

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

There is several ways to achieve this, for example, using some as:

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 has python3 something as get_key_type(d2)? If not, is there a better (cleaner) way to ask if the key of a dictionary is of type str?

3 Answers
Related