Python Convert nested MutableMapping to nested dict

Issue

I have a nested MutableMapping that I wish to convert to a nested dictionary. When I say that I have a MutableMapping, I of course mean I have a class that inherits it. The structure sort of looks like:

'key': <myobject> where myobject is the MutableMapping with more nested myobject's

My current attempt at doing this has resulted in:

def __makeDict(c):
    c = dict(c)
    for item in c:
        if isinstance(c[item], MutableMapping):
            c[item] = Configuration.__makeDict(c[item])
            return c[item]
    return c

Feeding in the nested MutableMapping produces only the bottom most level of the tree (which I think I understand). The question is, how can I iterate over this and produce the correct result? Any input is appreciated, cheers.

Solution

def __makeDict(c):
    for item in c:
        if isinstance(c[item], MutableMapping):
            Configuration.__makeDict(c[item])
            c[item] = dict(c[item])

    return dict(c)

I figured it out. I re-arranged the order to use the mutating powers of MutableList() to help rebuild the dictionary.

Answered By – Joshua Gilman

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published