我有一个 JSON 文件,例如:
{
"items": {
"item1": {
"thing1": "SomeValue",
"thing2": "AnotherValue"
},
"item2": {
"thing1": "SomeValue",
"thing2": "AnotherValue"
},
"item3": {
"thing1": {
"moreStuff": "someStuff",
"evenMoreStuff": "someMoreStuff"
}
}
}
}
我想通过将字符串列表作为键传递来创建一个通用函数来更新文件中的单个值。
def update_dict(value, keys):
with open(somePath, "r") as f:
data = json.load(f)
data[keys[0]][keys[1]][keys[2]] = value
with open(somePath, "w") as f:
json.dump(data, f,
value = "AThirdValue"
keys = ["items", "item2", "thing1"]
update_dict(value, keys)
我想不通的是,如果一个人不知道密钥列表的长度,如何做到这一点。例如,这将不起作用:
value = "AThirdValue"
keys = ["items", "item3", "thing1", "moreStuff"]
update_dict(value, keys)
如果我添加另一个深度级别,我不想使用 if 语句来检查长度,然后必须编辑此函数。