Python - Unflatten dict -
i have multi-dimensional dict:
a = {'a' : 'b', 'c' : {'d' : 'e'}} and written simple function flatten dict:
def __flatten(self, dictionary, level = []): tmp_dict = {} 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 function dict a in result:
{'a' : 'b', 'c.d' : 'e'} now, after making few instructions on flattened dict need build new, multi-dimensional dict flattened. example:
>> unflatten({'a' : 0, 'c.d' : 1)) {'a' : 0, 'c' : {'d' : 1}} the problem have not have function unflatten :)
can this? have no idea how 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 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 increases difficulty of task, know. thats why had problem , found no solution in hours..
def unflatten(dictionary): resultdict = dict() key, value in dictionary.iteritems(): parts = key.split(".") d = resultdict part in parts[:-1]: if part not in d: d[part] = dict() d = d[part] d[parts[-1]] = value return resultdict
Comments
Post a Comment