use list values as keys to dict with keys

Question:

I have a dictionary

foo = {"/" : {"bar":"returnme"} }

and a list

example  = ["/","bar"]

how do I use the list to return the value in "bar" ? (i.e. identical output to
foo["/"]["bar"] )

For clarity the value of the example list changes, the example could also be:

foo = {"/" : {"bar": {"morefoo": {"returnme"}} }} 

example = ["/","bar","morefoo"]

foo[example] –> "returnme"

For other functionality in the script I will need to be able to use the example list to add/remove things to the ‘final’ dictionary.

Answers:

You have to iteratively retrieve elements from a dictionary.

def get(tree, keys):
    current = tree
    for key in keys:
        current = current[key]
    return current

and it works:

>>> get({"/": {"bar": "returnme"}}, ["/", "bar"])
'returnme'
>>> get({"/": {"bar": {"morefoo": "returnme"}}}, ["/", "bar", "morefoo"])
'returnme'
>>>
Answered By: jthulhu
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.