Skip to content

Flatten Dictionary Python | Example code

  • by

How to convert given a nested dictionary into a flattened dictionary where the key is separated by ‘_’ in case of the nested key is to be started.

Suppose the given dictionary is:

{'a': 1,
 'c': {'a': 2,
       'b': {'x': 5,
             'y' : 10}},
 'd': [1, 2, 3]}

Flatten Dictionary should look like:-

{'a': 1,
 'c_a': 2,
 'c_b_x': 5,
 'c_b_y': 10,
 'd': [1, 2, 3]}

Example Flatten Dictionary Python

Simple example code. Basically, the same way you would flatten a nested list, just iterating the dict by key/value, creating new keys for a new dictionary, and creating the dictionary at the final step.

import collections


def flatten(d, parent_key='', sep='_'):
    items = []
    for k, v in d.items():
        new_key = parent_key + sep + k if parent_key else k
        if isinstance(v, collections.MutableMapping):
            items.extend(flatten(v, new_key, sep=sep).items())
        else:
            items.append((new_key, v))
    return dict(items)


dict1 = {'a': 1,
         'c': {'a': 2,
               'b': {'x': 5,
                     'y': 10}},
         'd': [1, 2, 3]}

print(flatten(dict1))

Output:

Flatten Dictionary Python

Another Example

If using pandas, You can do it with json_normalize() like so:

import pandas as pd

d = {'a': 1,
     'c': {'a': 2, 'b': {'x': 5, 'y' : 10}},
     'd': [1, 2, 3]}

df = pd.json_normalize(d, sep='_')

print(df.to_dict(orient='records')[0])

Output: {‘a’: 1, ‘d’: [1, 2, 3], ‘c_a’: 2, ‘c_b_x’: 5, ‘c_b_y’: 10}

Source: stackoverflow.com

Do comment if you have any doubts and suggestions on this Python Dictionary topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading