简体   繁体   中英

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")

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM