Skip to content
Advertisement

Python – Unflatten dict

I have this multi-dimensional dict:

a = {'a' : 'b', 'c' : {'d' : 'e'}}

And written simple function to flatten that dict:

def __flatten(self, dictionary, level = []):
    tmp_dict = {}
    for key, val in dictionary.items():
        if type(val) == dict:
            tmp_dict.update(self.__flatten(val, level + [key]))
        else:
            tmp_dict['.'.join(level + [key])] = val
    return tmp_dict

After call this function with dict a i get in result:

{'a' : 'b', 'c.d' : 'e'}

Now, after making few instructions on this flattened dict i need to build new, multi-dimensional dict from that flattened. Example:

>> unflatten({'a' : 0, 'c.d' : 1))
{'a' : 0, 'c' : {'d' : 1}}

The only problem I have is that i do not have a function unflatten :)
Can anyone help with this? I have no idea how to do it.

EDIT:

Another example:

{'a' : 'b', 'c.d.e.f.g.h.i.j.k.l.m.n.o.p.r.s.t.u.w' : 'z'}

Should be after unflatten:

{'a': 'b', 'c': {'d': {'e': {'f': {'g': {'h': {'i': {'j': {'k': {'l': {'m': {'n': {'o': {'p': {'r': {'s': {'t': {'u': {'w': 'z'}}}}}}}}}}}}}}}}}}}

And another:

{'a' : 'b', 'c.d' : 'z', 'c.e' : 1}

To:

{'a' : 'b', 'c' : {'d' : 'z', 'e' : 1}}

This greatly increases the difficulty of the task, i know. Thats why i had problem with this and found no solution in hours..

Advertisement

Answer

def unflatten(dictionary):
    resultDict = dict()
    for key, value in dictionary.items():
        parts = key.split(".")
        d = resultDict
        for part in parts[:-1]:
            if part not in d:
                d[part] = dict()
            d = d[part]
        d[parts[-1]] = value
    return resultDict
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement