1

I have a nested python dictionary with a variable depth. I know each key and the depth of the item I want to change. How can I change this variable in a function if the depth of the variable can change?

For example:

I have the following python dictionary:

myfamily = {
  "child1" : {
    "name" : "Emil",
    "year" : 2004,
    "grandchild1" : {
           "name" : "Emil",
           "year" : 2004
    }
  },
  "child2" : {
    "name" : "Tobias",
    "year" : 2007
  },
  "child3" : {
    "name" : "Linus",
    "year" : 2011
  }
}

I know I can change a value with

myfamily["child1"]["name"] = "Tom"

But what If child1 has another child and this one has another child... When starting the program I don't know how many grand childs and great grand childs etc. there are.

So I want a function like

path = {"child1", "grandchild1", "name"}
depth = len(path)
def changeItem(myfamily, path, depth)
    myfamily[]...[][] = "Tom"
Sebrotec
  • 23
  • 5

0 Answers0