I have a class called nesteddict derived from collections.defaultdict that hold a nested set of dictionaries:
import collections
class nesteddict(collections.defaultdict):
"""Nested dictionary structure.
Based on Stack Overflow question 635483
"""
def __init__(self):
collections.defaultdict.__init__(self, nesteddict)
self.locked = False
I would like to be able to perform an operation an instance that converts all of the nesteddict objects to python-native dict objects.
One way to do this is to have a method:
def todict(self):
for (key,val) in self.iteritems():
if isinstance(val,nesteddict):
val.todict()
self[key] = dict(val)
self = dict(self)
This is successful at replacing all the inner mapping objects with dict types, but the last statement in the method is obviously not going to work.
Here is an example:
In [93]: a = pyutils.nesteddict()
In [94]: a[1][1] = 'a'
In [95]: a[1][2] = 'b'
In [96]: a[2][1] = 'c'
In [97]: a[2][2] = 'd'
In [98]: print a
defaultdict(<class 'pyutils.nesteddict'>, {1: defaultdict(<class 'pyutils.nesteddict'>, {1: 'a', 2: 'b'}), 2: defaultdict(<class 'pyutils.nesteddict'>, {1: 'c', 2: 'd'})})
In [99]: a.todict()
In [100]: print a
defaultdict(<class 'pyutils.nesteddict'>, {1: {1: 'a', 2: 'b'}, 2: {1: 'c', 2: 'd'}})
Is there a way to do this in python? Have a method that converts its object to another type? If not, what is a good alternative to this. Note that the datatype in practice may be large, so it would be preferable not to just make a copy and then return it.
Thanks!
Uri