简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM