简体   繁体   中英

How to get to a dict key from a list?

lets say I have the following dict structure and a list of keys.

d = {
    'a': {
        'b': {
            'c': 'value'
        }
    }
}
keyList = ['a', 'b', 'c']

What is a pythonic way to reference the value of the c key in a dynamic way? In a static way I would say something like d[a][b][c] however if my keyList is dynamic and I need to reference the value at runtime is there a way to do this? the len of keyList is variable.

The main problem is i really don't know what to search. I tried things like dynamic dictionary path but couldn't get anything remotely close

You can use functools.reduce with the input dict as the starting value and dict.get as the reduction function:

from functools import reduce

print(reduce(dict.get, keyList, d))

This outputs:

value

Demo: https://replit.com/@blhsing/QuintessentialAntiqueMath

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