convert flatten dict to nested dict

Question:

I use this function to convert nested dict to flatten dict:

make_flatten_dict = lambda d, sep: pd.json_normalize(d, sep=sep).to_dict(orient='records')[0]

input:

d = {‘a’: 1,
‘c’: {‘a’: ‘#a_val’, ‘b’: {‘x’: ‘#x_value’, ‘y’ : ‘#y’}},
‘d’: [1, ‘#d_i1’, 3]}

output:

{‘a’: 1, ‘d’: [1, ‘#d_i1’, 3], ‘c.a’: ‘#a_val’, ‘c.b.x’: ‘#x_value’, ‘c.b.y’: ‘#y’}

How I can build input from the output?

Asked By: alihejrati

||

Answers:

For each multi-key you need to build the tree, add a {} for each one except the last, then use the last one to assign the value

value = {'a': 1, 'd': [1, '#d_i1', 3], 'c.a': '#a_val', 'c.b.x': '#x_value', 'c.b.y': '#y'}

result = {}
for k, v in value.items():
    tmp = result
    *keys, last = k.split(".")
    for key in keys:
        tmp = tmp.setdefault(key, {})
    tmp[last] = v

print(result)
# {'a': 1, 'd': [1, '#d_i1', 3], 'c': {'a': '#a_val', 'b': {'x': '#x_value', 'y': '#y'}}}
Answered By: azro
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.