dictionary - What happens when I loop a dict in python -


i know python return key list when put dict in for...in... syntax.

but what happens dict?

when use help(dict), can not see __next()__ method in method list. if want make derived class based on dict:

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

and return value list for...in...

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

what should do?

naively, if want iteration on instance of myclass yield values instead of keys, in myclass define:

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

in python 3:

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

but beware! doing class no longer implements contract of collections.mutablemapping, though issubclass(myclass, collections.mutablemapping) true. might better off not subclassing dict, if behaviour want, instead have attribute of type dict hold data, , implement functions , operators need.


Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -