Home > Backend Development > Python Tutorial > How to Flatten Nested Dictionaries with Compressed Keys in Python?

How to Flatten Nested Dictionaries with Compressed Keys in Python?

Susan Sarandon
Release: 2024-12-16 02:24:10
Original
819 people have browsed it

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]}
Copy after login

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]}
Copy after login

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)
Copy after login

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}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template