Home > Backend Development > Python Tutorial > How Can I Flatten a Nested Dictionary in Python?

How Can I Flatten a Nested Dictionary in Python?

Patricia Arquette
Release: 2024-12-17 00:59:24
Original
869 people have browsed it

How Can I Flatten a Nested Dictionary in Python?

Unraveling the Complexities: Flattening Nested Dictionaries

Suppose you encounter a intricate dictionary with nested levels, mirroring the tangled structure of a labyrinth. To traverse this dictionary, one must employ a clever technique to flatten it, unraveling its intricate layers into a simplified form. This simplified rendition unveils the underlying data in a more accessible and straightforward manner.

The key to this simplification lies in iterating over both the keys and values of the dictionary. Through this process, new keys are meticulously constructed by concatenating the parent key with the current key, separated by a customizable delimiter.

If a value itself happens to be a dictionary, the flattening process is recursively applied, seamlessly incorporating its elements into the flattened structure. However, if the value is not a dictionary, it is directly appended to the flattened dictionary.

In essence, the values contained within the intricate web of nested dictionaries are meticulously extracted and adorned with newly assigned keys, reflecting their hierarchical relationships. The result is a flattened dictionary, akin to a neatly organized map, where each value can be effortlessly located by its unique, newly assigned key.

To further illustrate this flattening technique, consider the following example:

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

When applied to a dictionary like:

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

The result is a flattened dictionary:

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

Utilizing this flattening technique, one effectively unravels the complexities of nested dictionaries, revealing the hidden structure within. This streamlined representation empowers developers with a more accessible and manageable data format, facilitating tasks like data analysis, querying, and data manipulation.

The above is the detailed content of How Can I Flatten a Nested Dictionary 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