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

2024-10-02 18:19:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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"]

但我想知道是否有一个更优雅的方式来实现这一点


Tags: orthepathtest元素anotherlevelone
2条回答

您可以尝试以下方法:

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'}}

相关问题 更多 >