Skip to content

Latest commit

 

History

History
72 lines (46 loc) · 2.37 KB

Python_Flatten_nested_dict.md

File metadata and controls

72 lines (46 loc) · 2.37 KB



Template request | Bug report | Generate Data Product

Tags: #python #dict #flatten #nested #data #structure

Author: Florent Ravenel

Description: This notebook will show how to flatten a nested dict in Python.

References:

Input

Import libraries

Setup Variables

# Setup a nested dict
nested_dict = {"key1": 1, "key2": {"key3": 1, "key4": {"key5": 4}}}

Model

Flatten nested dict

# Flatten the nested dict
def flatten_dict(d, parent_key='', sep='_'):
    """
    Flattens a nested dictionary into a single level dictionary.

    Args:
        d (dict): A nested dictionary.
        parent_key (str): Optional string to prefix the keys with.
        sep (str): Optional separator to use between parent_key and child_key.

    Returns:
        dict: A flattened dictionary.
    """
    items = []
    for k, v in d.items():
        new_key = f"{parent_key}{sep}{k}" if parent_key else k
        if isinstance(v, dict):
            items.extend(flatten_dict(v, new_key, sep=sep).items())
        else:
            items.append((new_key, v))
    return dict(items)


flatten_dict = flatten_dict(nested_dict)

Output

Display result

# Display the flatten dict
flatten_dict