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:
# Setup a nested dict
nested_dict = {"key1": 1, "key2": {"key3": 1, "key4": {"key5": 4}}}
# 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)
# Display the flatten dict
flatten_dict