So I\'m writing a class that extends a dictionary which right now uses a method \"dictify\" to transform itself into a dict. What I would like to do instead though is change it
You need to override __iter__
.
def __iter__(self):
return iter((k, (v.dictify() if isinstance(v, dict) else v))
for (k, v) in self.items())
Instead of self.items()
, you should use self.iteritems()
on Python 2.
Edit: OK, This seems to be your problem:
>>> class B(dict): __iter__ = lambda self: iter(((1, 2), (3, 4)))
...
>>> b = B()
>>> dict(b)
{}
>>> class B(list): __iter__ = lambda self: iter(((1, 2), (3, 4)))
...
>>> b = B()
>>> dict(b)
{1: 2, 3: 4}
So this method doesn't work if the object you're calling dict()
on is a subclass of dict.
Edit 2: To be clear, defaultdict
is a subclass of dict
. dict(a_defaultdict) is still a no-op.