3

I need to access a dictionary in Python depending on a list. Example:

lst = ['A', 'B', 'C']

Then the dictionary accessing should be:

d['A']['B']['C']

The list can be of any depth/elements.

What is the best way to tackle this problem?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
John
  • 41
  • 1
  • 4

2 Answers2

2

I would create a function that iterates through the list:

d = {}
d['A'] = {}
d['A']['B'] = {}
d['A']['B']['C'] = 'value'
lst = ['A', 'B', 'C']

def get_value(d, lst):
    for elem in lst:
        d = d[elem]
    return d

print get_value(d, lst)  # outputs 'value'
francisco sollima
  • 7,952
  • 4
  • 22
  • 38
2

One may also use the eval function applied to a string generated from the list:

eval('d[\''+'\'][\''.join(lst)+'\']')

here '\'][\'' is a delimiter

freude
  • 3,632
  • 3
  • 32
  • 51