There are multiple ways. Here is one way to do it.
nested_dict = {
'a': {
'b': 1,
'c': {
'd': 2
}
},
'b': 3,
'c': {
'd': 4,
'a': 5
},
}
flatten_dict = {}
def flatten_the_nested(nested_dict, parent_key=''):
for key, value in nested_dict.items():
new_key = parent_key + '.' + key if parent_key is not '' else key
if isinstance(value, dict):
flatten_the_nested(value, new_key)
else:
flatten_dict[new_key] = value
return flatten_dict
print(flatten_the_nested(nested_dict, ''))
You will get the following result.
{'c.d': 4, 'c.a': 5, 'b': 3, 'a.b': 1, 'a.c.d': 2}
Or if you want to use some library then you can use https://pypi.org/project/flatten-dict/