Build a nested dict in python

Given X = [[‘A’, ‘B’, ‘C’], [‘A’, ‘B’, ‘D’]]
generate Y = {‘A’: {‘B’: {‘C’: {}, ‘D’: {}}}}

This has real-life applications say when you want to build a lookup tree for a file directory.

I thought using a recursive call would be the right way, but I had a hard time passing a node down to the next recursive call. It turns out there is no need to use a recursive function.

X = [['A', 'B', 'C'], ['A', 'B', 'D']]
Y = {}
for path in X:
    current_level = Y
    for part in path:
        if part not in current_level:
            current_level[part] = {}
        current_level = current_level[part]

ref: https://stackoverflow.com/questions/7653726/how-to-turn-a-list-into-nested-dict-in-python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s