Converting a list to a nested dictionary?

What's the most pythonic way to convert:

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

      

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

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

      

where y is some variable.

+3


source to share


1 answer


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 option 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'}}}}}

      

+3


source







All Articles