Reputation: 29
Below is my data.
input = {'key1': {'key1.1': 'value1.1',
'key1.2': 'value1.2',
'key1.3': {'key1.3.1': 'value1.3.1', 'key1.3.2': [{'key1.3.2.1': 'value1.3.2.1'},
{'key1.3.2.2': 'value1.3.2.2'}
]
}
},
'key2': 'value2'}
I want to recursively convert inner inner key/values into a list of sub dictionaries with Name and Value as their keys. Below is my desired output.
output = {"key1": [{"NAME": "key1.1", "VALUE": "value1.1"},
{"NAME": "key1.2", "VALUE": "value1.2"},
{"NAME": "key1.3", "VALUE": [{"NAME": "key1.3.1", "VALUE": "value1.3.1"},
{"NAME": "key1.3.2", "VALUE": [{"NAME": "key1.3.2.1", "VALUE": "value1.3.2.1"},
{"NAME": "key1.3.2.2", "VALUE": "value1.3.2.2"}]
}]
}],
"key2": "value2"}
Below is what is tried but it is not working correctly for list of dictionaries (ex: "key1.3.2.1": "value1.3.2.1"). Is there a way to achieve this output?
def my_func(d):
new_dict = {}
for k, v in d.items():
a = []
if isinstance(v, dict):
for key, value in my_func(v).items():
x = {}
y = {}
x['NAME'] = key
y['VALUE'] = value
z = {**x, **y}
a.append(z)
elif isinstance(v, list):
a = [my_func(item) if isinstance(item, dict) else item for item in v]
else:
a = v
new_dict[k] = a
return new_dict
output = json.dumps(my_func(input), indent=2)
print(output)
Upvotes: 0
Views: 56
Reputation: 9061
You can use recursive function
def fun(d, res=None):
if res is None:
res = []
for k, v in d.items():
if isinstance(v, dict):
res.append({'NAME': k, 'VALUE': fun(v)})
elif isinstance(v, list):
temp = {'NAME': k, 'VALUE': []}
for x in v:
temp['VALUE'].append(fun(x)[0])
res.append(temp)
else:
res.append({'NAME': k, 'VALUE': v})
return res
d = {k: fun(v) if isinstance(v, dict) else v for k, v in d.items()}
print(d)
Output:
{'key1': [{'NAME': 'key1.1', 'VALUE': 'value1.1'},
{'NAME': 'key1.2', 'VALUE': 'value1.2'},
{'NAME': 'key1.3',
'VALUE': [{'NAME': 'key1.3.1', 'VALUE': 'value1.3.1'},
{'NAME': 'key1.3.2',
'VALUE': [{'NAME': 'key1.3.2.1', 'VALUE': 'value1.3.2.1'},
{'NAME': 'key1.3.2.2',
'VALUE': 'value1.3.2.2'}]}]}],
'key2': 'value2'}
Upvotes: 1