我有一个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"]
但我想知道是否有一个更优雅的方式来实现这一点
您可以尝试以下方法:
特别是你的意见:
您可以尝试:
输出:
相关问题 更多 >
编程相关推荐