Home >Backend Development >Python Tutorial >How Can I Flatten Nested Dictionaries and Compress Their Keys in Python?

How Can I Flatten Nested Dictionaries and Compress Their Keys in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-14 00:53:10191browse

How Can I Flatten Nested Dictionaries and Compress Their Keys in Python?

Flattening Nested Dictionaries: Compressing Keys

In the realm of data manipulation, encountering nested dictionaries can often pose a challenge when it comes to accessing data. One common scenario is the need to flatten these complex dictionaries, creating a simpler structure with compressed keys. Understanding how to perform this task effectively is crucial for efficient data analysis and management.

Consider a nested dictionary in the following format:

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

Our goal is to transform this dictionary into a flattened version where keys are compressed to reflect their hierarchical structure:

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

To achieve this, we can leverage a flattening algorithm. The approach involves iterating through the dictionary, creating new keys by concatenating parent keys with child keys and a separator, and ultimately generating a new flattened dictionary.

Implementing this algorithm in Python involves utilizing the collections.abc.MutableMapping base class to handle different dictionary types. Here's a Python implementation:

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)

>>> 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}

By utilizing this algorithm, we can effectively flatten nested dictionaries, compressing keys to provide a simplified data structure for more efficient data management and analysis.

The above is the detailed content of How Can I Flatten Nested Dictionaries and Compress Their Keys in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn