I have this multi-dimensional dict:
JavaScript
x
2
1
a = {'a' : 'b', 'c' : {'d' : 'e'}}
2
And written simple function to flatten that dict:
JavaScript
1
9
1
def __flatten(self, dictionary, level = []):
2
tmp_dict = {}
3
for key, val in dictionary.items():
4
if type(val) == dict:
5
tmp_dict.update(self.__flatten(val, level + [key]))
6
else:
7
tmp_dict['.'.join(level + [key])] = val
8
return tmp_dict
9
After call this function with dict a
i get in result:
JavaScript
1
2
1
{'a' : 'b', 'c.d' : 'e'}
2
Now, after making few instructions on this flattened dict i need to build new, multi-dimensional dict from that flattened. Example:
JavaScript
1
3
1
>> unflatten({'a' : 0, 'c.d' : 1))
2
{'a' : 0, 'c' : {'d' : 1}}
3
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:
JavaScript
1
2
1
{'a' : 'b', 'c.d.e.f.g.h.i.j.k.l.m.n.o.p.r.s.t.u.w' : 'z'}
2
Should be after unflatten:
JavaScript
1
2
1
{'a': 'b', 'c': {'d': {'e': {'f': {'g': {'h': {'i': {'j': {'k': {'l': {'m': {'n': {'o': {'p': {'r': {'s': {'t': {'u': {'w': 'z'}}}}}}}}}}}}}}}}}}}
2
And another:
JavaScript
1
2
1
{'a' : 'b', 'c.d' : 'z', 'c.e' : 1}
2
To:
JavaScript
1
2
1
{'a' : 'b', 'c' : {'d' : 'z', 'e' : 1}}
2
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
JavaScript
1
12
12
1
def unflatten(dictionary):
2
resultDict = dict()
3
for key, value in dictionary.items():
4
parts = key.split(".")
5
d = resultDict
6
for part in parts[:-1]:
7
if part not in d:
8
d[part] = dict()
9
d = d[part]
10
d[parts[-1]] = value
11
return resultDict
12