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

How Do I Flatten a Nested Dictionary in Python?

Barbara Streisand
Release: 2024-12-15 08:56:09
Original
226 people have browsed it

How Do I Flatten a Nested Dictionary in Python?

Flattening Nested Dictionaries: Compressing Keys

To flatten a nested dictionary, you'll need to recursively iterate through each key and value pair, creating new keys by concatenating the parent key with the current key using a separator, such as an underscore.

Deeper levels of the nested dictionary require further recursion using the same process.

Once you've completed the recursion, create a new dictionary from the flattened items.

Here's an example implementation using Python's collections.abc.MutableMapping:

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

Example usage:

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

The above is the detailed content of How Do 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