开发者

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] ho开发者_StackOverflow社区wever 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


d = {
    'a': {
        'b': {
            'c': 'value'
        }
    }
}

key_list = ['a', 'b', 'c']

# Use the `get` method to traverse the dictionary and get the value at the specified path
value = d
for key in key_list:
    value = value.get(key, {}) # suggested by @sahasrara62

# Print the value
print(value)  # Output: 'value'


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜