user4018217
user4018217

Reputation:

Converting a list to a nested dictionary?

What is the most pythonic way to convert:

A = [a1, a2, a3, a4, a5]

where "A" can be a list with any number of elements to

B = {a1: {a2: {a3: {a4: {a5: y}}}}}

where y is some variable.

Upvotes: 3

Views: 82

Answers (1)

falsetru
falsetru

Reputation: 369044

def build_dict(A, y):
    for s in reversed(A):
        y = {s: y}
    return y

A = ['a1', 'a2', 'a3', 'a4', 'a5']
y = 'some value'
print(build_dict(A, y))

output:

{'a1': {'a2': {'a3': {'a4': {'a5': 'some value'}}}}}

Alternative using reduce (functools.reduce in Python 3.x):

>>> A = ['a1', 'a2', 'a3', 'a4', 'a5']
>>> y = 'some value'
>>> reduce(lambda x, s: {s: x}, reversed(A), y)
{'a1': {'a2': {'a3': {'a4': {'a5': 'some value'}}}}}

Upvotes: 3

Related Questions