Dev Helpers
← Back

Rebuild a nested dictionary from path tuples

Rebuild a nested dictionary from path tuples using Python lists and dictionaries.

Open this example in the interactive library

Source code

root = {}
for path, value in [(('ui', 'mode'), 'dark'), (('ui', 'zoom'), 2)]:
    branch = root
    for key in path[:-1]:
        branch = branch.setdefault(key, {})
    branch[path[-1]] = value
print(root)

Sample output

{'ui': {'mode': 'dark', 'zoom': 2}}