[Python] How can I flatten a deeply nested dictionary with dot notation in Python?

Discussão em 'Python' iniciado por Stack, Junho 25, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to flatten a nested dictionary in Python where the depth is not fixed. The goal is to convert it into a single-level dictionary using dot notation to represent the nested keys.

    Input:

    nested_dict = {
    'a': {
    'b': {
    'c': 1
    },
    'd': 2
    },
    'e': 3
    }


    This is the output I want:

    {
    'a.b.c': 1,
    'a.d': 2,
    'e': 3
    }


    I’ve tried a recursive approach, but it gets messy with deeper levels, and I’m not sure it handles all edge cases properly. I’d appreciate a clean and efficient way to achieve this—ideally something that works regardless of how deeply the dictionary is nested.

    def flatten_dict(d, parent_key='', sep='.'):
    items = {}
    for k, v in d.items():
    new_key = f"{parent_key}{sep}{k}" if parent_key else k
    if isinstance(v, dict):
    items.update(flatten_dict(v, new_key, sep=sep))
    else:
    items[new_key] = v
    return items

    Continue reading...

Compartilhe esta Página