0

I have nested dict like:

tdict = {folder': {'file0.txt': 222, 'subfolder': {'file1.txt': 333}}, 'file00.txt': 111}

and it can go deeper

How to iterate throw existing dict and add for ex. new item 'file2', described by list:

path_list = ['folder', 'subfolder', 'file2']
Evgeniy
  • 193
  • 3
  • 19

2 Answers2

1

This function will add a file if value isn't None, but will add a new directory otherwise:

def add_path(parent, path, value=None):
    end = len(path) - 1
    for index, component in enumerate(path):
        if index < end or value is None:
            parent = parent.setdefault(component, {})
        else:
            parent[component] = value
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
0

I assume you want to keep the dictionary structure. So, what you want to do is iterate through the list:

currItem = tdict
for item in path_list:
    if item not in currItem:
        currItem[item] = value
    else:
        currItem = currItem[item]

Depending on how you want to define your input list 'syntax' you will need to decide what to put in the value variable.

Spencer Rathbun
  • 14,510
  • 6
  • 54
  • 73