我有一个看起来像这样的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'}}
你可以试试:
def get_by_path(my_dict, path):
if len(path) == 1:
return my_dict[path[0]]
return get_by_path(my_dict[path[0]], path[1:])
dummy = {
"fieldone": {
"fieldtwo": {
"yetanother": {
"another-nested-one": "the-deepest-nested"
}
}
}
}
my_path = ("fieldone", "fieldtwo")
print(get_by_path(dummy , my_path))
输出:
{'yetanother': {'another-nested-one': 'the-deepest-nested'}}