Home >Backend Development >Python Tutorial >How to Flatten Nested Dictionaries with Compressed Keys in Python?
Flattening Nested Dictionaries with Compressed Keys
Consider a hierarchical dictionary structure like the one below:
{'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]}
To flatten this into a streamlined structure like:
{'a': 1, 'c_a': 2, 'c_b_x': 5, 'c_b_y': 10, 'd': [1, 2, 3]}
involves flattening both the nested list and the nested dictionaries within.
Approach
This procedure parallels the steps for flattening a nested list. However, it requires additional processing for iterating through the dictionary, generating unique key names for the flattened structure using a separator, and assembling the new dictionary.
Implementation
Using collections.abc.MutableMapping for dictionary type checking, the following code snippet utilizes recursion to traverse the nested structure and construct the compressed representation:
from collections.abc import MutableMapping def flatten(dictionary, parent_key='', separator='_'): items = [] for key, value in dictionary.items(): new_key = parent_key + separator + key if parent_key else key if isinstance(value, MutableMapping): items.extend(flatten(value, new_key, separator=separator).items()) else: items.append((new_key, value)) return dict(items)
Applying this method to the given example dictionary produces the desired flattened representation:
>>> flatten({'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]}) {'a': 1, 'c_a': 2, 'c_b_x': 5, 'd': [1, 2, 3], 'c_b_y': 10}
This technique efficiently flattens nested dictionaries by compressing the key names using a separator, providing a compact and easily traversable structure.
The above is the detailed content of How to Flatten Nested Dictionaries with Compressed Keys in Python?. For more information, please follow other related articles on the PHP Chinese website!