Get dictionary key type

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

For example, I want to decide if one of these dictionaries has keys like 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 some of them:

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

But this is quite annoying because it is d2.keys()not indexed, so you need to convert it to a list in order to extract the key value.

So python3 is something like get_key_type(d2)? If not, is there a better (cleaner) way to find out if the dictionary key has a type str?

+5
source share
4 answers

, , , dict:

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

, :

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

, . ( @Duncan)

, dicts:

/

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

, d2.keys(), :

<class 'dict_keys'>

, - .

+6

d1.keys() <class 'dict_keys'>, ,

>>> 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]

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

this out

+1

, , :

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

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

set(map(type, ...)) , :

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

{str} - , , str. True, False .

0
source

@MSeifert your answer was helpful. How about checking the type of "values"?

0
source

Source: https://habr.com/ru/post/1681200/


All Articles