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
edit: As ironchefpython pointed out in comments, this isn't actually doing what I thought it did, as in my example b[1]
is still a RecursiveDict
. This may still be useful, as you essentially get an object pretty similar Rob Cowie's answer, but it is built on defaultdict
.
You can get the behavior you want (or something very similar) by overriding __repr__
, check this out:
class RecursiveDict(defaultdict):
def __init__(self):
super(RecursiveDict, self).__init__(RecursiveDict)
def __repr__(self):
return repr(dict(self))
>>> a = RecursiveDict()
>>> a[1][2][3] = 4
>>> a # a looks like a normal dict since repr is overridden
{1: {2: {3: 4}}}
>>> type(a)
>>> b = dict(a)
>>> b # dict(a) gives us a normal dictionary
{1: {2: {3: 4}}}
>>> b[5][6] = 7 # obviously this won't work anymore
Traceback (most recent call last):
File "", line 1, in
KeyError: 5
>>> type(b)
There may be a better way to get to a normal dictionary view of the defaultdict
than dict(self)
but I couldn't find one, comment if you know how.