1
>>> d = {'m': 'mango', 'f': 'fish', 'a': 'apple'}
>>> d
{'m': 'mango', 'f': 'fish', 'a': 'apple'}
>>> d.keys()
dict_keys(['m', 'f', 'a'])
>>> for x in d.keys(): print(x)
m
f
a
>>> |

What is dict_keys() and how to override this in a method (the way __iter__ is overridden)?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Patt Mehta
  • 4,110
  • 1
  • 23
  • 47

1 Answers1

3

dict_keys() is a dictionary view object; such objects are iterables (meaning you can create multiple independent iterators for such an object, using iter()).

You can return your own implementation of such an object from a .keys() method. The specific type returned by dict.keys() is not available for re-use, you'll have to implement your own from scratch.

I covered creating your own in a previous answer; there are a fair number of methods to cover.

Note that generator functions are merely a technique to create an iterator using a Python function. All generator functions produce an iterator when called, but not all iterators are generator iterators. You can also create iterators with a generator expression, or by including an __iter__ method that returns self and a __next__ method that produces one of the items each time it is called.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343