In Python3, what type should I use to check if the dictionary keys belong to it?
>>> d = {1 : 2}
>>> type(d.keys())
<class 'dict_keys'>
So naturally I tried this:
>>> isinstance(d.keys(), dict_keys)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'dict_keys' is not defined
What should I put in place of the explicit dict_keys
as 2nd argument for isinstance
?
(This is useful as I have to handle unknown input variables that can take the form of dictionary keys. And I know using list(d.keys())
can convert to a list (recovering Python2 behavior) but that's not an option in this case.)
You can use collections.abc.KeysView
:
In [19]: isinstance(d.keys(), collections.abc.KeysView)
Out[19]: True
collections.abc
module provides abstract base classes that can be used to test whether a class provides a particular interface
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With