I get some override elements providen with this kind of structure:
(keys, value)
I would like to use that to change value in nested object (dict and list). It could look like this:
data[keys[0]][keys[1]][keys[2]] = value
The hard point is, the number of keys can be variable. I have no clue how to manage this recursively.
CodePudding user response:
A functional approach using functools.reduce
and operator.getitem
from functools import reduce
from operator import getitem
data = {"a": {"b": {"c": 1}}}
keys = ["a", "b", "c"]
*suffix, key = keys
reduce(getitem, suffix, data)[key] = 2
print(data)
Output
{'a': {'b': {'c': 2}}}
CodePudding user response:
You can do the following (iteratively):
def setkeys(data, keys, value):
*path, last = keys
for key in path:
data = data[key]
data[last] = value
Or for a recursive solution:
def setkeys(data, keys, value):
head, *tail = keys
if tail:
setkeys(data[head], tail, value)
else:
data[head] = value