Dev Helpers
← Back

Flatten a tree to dotted configuration paths

Flatten a tree to dotted configuration paths using Python lists and dictionaries.

Open this example in the interactive library

Source code

def leaves(tree, path=()):
    for key, value in tree.items():
        current = (*path, key)
        if isinstance(value, dict):
            yield from leaves(value, current)
        else:
            yield '.'.join(current), value
print(dict(leaves({'ui': {'theme': 'dark'}, 'port': 80})))

Sample output

{'ui.theme': 'dark', 'port': 80}