3

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.

falsetru
  • 357,413
  • 63
  • 732
  • 636

1 Answers1

3
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'}}}}}
falsetru
  • 357,413
  • 63
  • 732
  • 636