jstnknt
jstnknt

Reputation: 167

Python - "map" a list of keys to a dictionary

I have a multidimensional dictionary in Python, and I have a list which has the keys that I want to access. What is the easiest way to get the value from the dictionary?

Example:

main = {
    'one': {
        'two': {
            'three': "Final word"
        }
    }
}

mylist = ['one', 'two', 'three']

# and I want to print out the value of `three` ("Final word")

Upvotes: 3

Views: 222

Answers (2)

Valentin Lorentz
Valentin Lorentz

Reputation: 9753

An equivalent to mhlester's solution, with a taste of functional programming:

import operator
print reduce(operator.getitem, mylist, main)

Upvotes: 3

mhlester
mhlester

Reputation: 23231

Loop over mylist, storing an intermediate dict (I called it submain) until you run out of mylist elements:

submain = main
for key in mylist:
    submain = submain[key]
print submain

Upvotes: 7

Related Questions