I have a JSON file, for example:
{
"items": {
"item1": {
"thing1": "SomeValue",
"thing2": "AnotherValue"
},
"item2": {
"thing1": "SomeValue",
"thing2": "AnotherValue"
},
"item3": {
"thing1": {
"moreStuff": "someStuff",
"evenMoreStuff": "someMoreStuff"
}
}
}
}
I want to make a generic function to update a single value in the file by passing a list of strings as keys.
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)
What I can't figure out is how this can be done if one does not know the length of the keys list. For example this would not work:
value = "AThirdValue"
keys = ["items", "item3", "thing1", "moreStuff"]
update_dict(value, keys)
I would not want to use if-statements to check the length and then having to edit this function if I add another level of depth.