Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the types of the keys in a dictionary

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?

like image 406
Rockcat Avatar asked Jul 11 '17 14:07

Rockcat


1 Answers

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.

like image 116
MSeifert Avatar answered Oct 09 '22 20:10

MSeifert