gpt4 book ai didi

python - 如何在 JSON 中保存元素的位置

转载 作者:行者123 更新时间:2023-12-01 07:23:03 25 4
gpt4 key购买 nike

我有一个如下所示的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com