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?
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?
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'
One may also use the eval
function applied to a string generated from the list:
eval('d[\''+'\'][\''.join(lst)+'\']')
here '\'][\''
is a delimiter