作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个如下所示的 JSON:
dummy = {
"fieldone": {
"fieldtwo": {
"yetanother": {
"another-nested-one": "the-deepest-nested"
}
}
}
}
为了访问特定元素,我会这样做:
s = dummy["fieldone"]["fieldtwo"]
print(s)
{'yetanother': {'another-nested-one': 'the-deepest-nested'}}
但是我的元素是深层嵌套的(当然比示例要多得多),所以我想以这种方式保存元素的路径:
path = ["fieldone"]["fieldtwo"]
test = dummy.get(path)
# or dummy[path]
# or dummy.path
print(test)
当我运行此命令时,我收到以下消息:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-57cff8dffc3a> in <module>
----> 1 path = ["fieldone"]["fieldtwo"]
2 test = dummy[path]
3 print(test)
TypeError: list indices must be integers or slices, not str
有什么方法可以保存元素的位置并在以后以这种方式检索它们吗?我可以通过无限的链条来做到这一点,例如:
my_element = dummy["level_one"]["level_two"]["level_three"]
但我想知道是否有更优雅的方法来实现这一点
最佳答案
你可以尝试这样的事情:
from functools import reduce
import operator
def getFromDict(dict, list):
return reduce(operator.getitem, list, dict)
特别是,根据您的输入:
path = ["fieldone", "fieldtwo"]
print(getFromDict(dummy, path))
#output: {'yetanother': {'another-nested-one': 'the-deepest-nested'}}
关于python - 如何在 JSON 中保存元素的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57593891/
我是一名优秀的程序员,十分优秀!