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?

2
  • It would be very helpful if you could provide a example case of real input and expected output. Commented Dec 19, 2017 at 19:20
  • What do you want to do if one of the keys is missing? Commented Dec 19, 2017 at 19:29

2 Answers 2

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'
Sign up to request clarification or add additional context in comments.

4 Comments

Why did you introduce a new variable instead of just rebinding d?
You're right, I edited the answer!
Is there a way to create a nested dictionary using the list? So if lst = [ 'A', 'B', 'C'] then the dict created would be d['A']['B']['C'] = {}
@John. Why not try something yourself, even if it is just Googling? Your original question was closed as a duplicate, and I am pretty sure this new one is too.
2

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

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

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

4 Comments

it has past the test
My mistake. I did not read carefully. Downvote removed even though this is still bad advice.
what may be a better advice considering that we know nothing about the list and dictionary and how do they match together
Iterating through the list so you can actually do some checks?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.