#Using pandas DataFrame
import pandas as pd
d = {'x': 1,
'y': {'a': 2, 'b': {'c': 3, 'd' : 4}},
'z': {'a': 2, 'b': {'c': 3, 'd' : 4}}}
dframe = pd.json_normalize(d, sep='_')
print(dframe.to_dict(orient='records')[0])
A dictionary in python contains one or multiple key-value pair sets of values. It can also be nested and contains multiple sets as a value for a key. You can read more about python dictionaries here.
We are using the pandas json_normalize() method and passing nested dictionary and separator values to flatten the dictionary. After flattening the dictionary we are converting the data frame to dictionary with orientation records.
def flatten_dict(my_dict, p_val=''):
final_dict = {}
for key, val in my_dict.items():
new_key = p_val + key
if isinstance(val, dict):
final_dict.update(flatten_dict(val, new_key + '_'))
else:
final_dict[new_key] = val
return final_dict
result = flatten_dict(
{
'x': 1,
'y': {'a': 2, 'b': {'c': 3, 'd' : 4}},
'z': {'a': 2, 'b': {'c': 3, 'd' : 4}}
},
''
)
print(result)
0 Comments