PaleNeutron PaleNeutron - 6 months ago 18
Python Question

What happens when I loop a dict in python

I know

will simply return the key list when I put a

But what what happens to the dict?

When we use
, we can not see
method in the method list. So if I want to make a derived class based on

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

and return the value list with

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

what should I do?


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.