PaleNeutron PaleNeutron - 2 months ago 4
Python Question

What happens when I loop a dict in python

I know

Python
will simply return the key list when I put a
dict
in
for...in...
syntax.

But what what happens to the dict?

When we use
help(dict)
, we can not see
__next()__
method in the method list. So if I want to make a derived class based on
dict
:

class MyDict(dict)
def __init__(self, *args, **kwargs):
super(MyDict, self).__init__(*args, **kwargs)


and return the value list with
for...in...


d = Mydict({'a': 1, 'b': 2})
for value in d:


what should I do?

Answer

Naively, if all you want is for iteration over an instance of MyClass to yield the values instead of the keys, then in MyClass define:

def __iter__(self):
    return self.itervalues()

In Python 3:

def __iter__(self):
    return iter(self.values())

But beware! By doing this your class no longer implements the contract of collections.MutableMapping, even though issubclass(MyClass, collections.MutableMapping) is True. You might be better off not subclassing dict, if this is the behaviour you want, but instead have an attribute of type dict to hold the data, and implement only the functions and operators you need.