Search code snippets, questions, articles...

Python code examples to flatten a nested dictionary

The code snippet contains different code examples to flatten a python dictionary. If you are using pandas in your project then you can use the below code.
#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])
Output
{
'x': 1,
'y_a': 2,
'y_b_c': 3,
'y_b_d': 4,
'z_a': 2,
'z_b_c': 3,
'z_b_d': 4
}

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.

Search Index Data (The code snippet can also be found with below search text)

flatten a dictionary in python
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)
Here we have created a python function that is not using any dependency package to flatten a python dictionary. The parameters that passed to the function flatten_dict() is the dictionary that you want to flatten
Was this helpful?
0 Comments
Programming Feeds
Learn something new everyday on Devsheet