[英]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?以动态方式引用 c 键的值的 pythonic 方法是什么? 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?在 static 方式中,我会说类似
d[a][b][c]
东西,但是如果我的 keyList 是动态的并且我需要在运行时引用该值,有没有办法做到这一点? the len of keyList is variable. keyList 的 len 是可变的。
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:您可以使用
functools.reduce
,将输入字典作为起始值,将dict.get
作为缩减值 function:
from functools import reduce
print(reduce(dict.get, keyList, d))
This outputs:这输出:
value
Demo: https://replit.com/@blhsing/QuintessentialAntiqueMath演示: https://replit.com/@blhsing/QuintessentialAntiqueMath
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.