convert each sub-dictionary in a nested dictionary to defaultdict in Python -
class mydict(dict): pass def nest_dict(dct): dct = mydict(dct) k, v in dct.items(): if isinstance(v, dict): dct[k] = mydict(v) nest_dict(v) return dct dct = {'a':{'b':{'c':'d'}}} print(type(nest_dict(dct)['a']['b']))
here's piece of code have now. want covert each sub-dictionary in nested dictionary child class of dict, mydict. however, recursion logic change first level of sub dictionary. how modify recursion function?
you're not updating nested structures properly, try:
def nest_dict(dct): dct = mydict(dct) k, v in dct.items(): if isinstance(v, dict): dct[k] = nest_dict(v) return dct dct = {'a': {'b': {'c': 'd'}}} print(type(dct['a']['b'])) # <class 'dict'> my_dct = nest_dict(dct) print(type(my_dct['a']['b'])) # <class '__main__.mydict'>
although i'd advise not extend dict
, use collections.mutablemapping
instead. on python 3.x it's moved collections.abc.mutablemapping
.
Comments
Post a Comment