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]


Leave a Reply

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

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

Facebook photo

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

Connecting to %s