How do I add a value to a specified path in the dictionary of python?

to implement a function, pass in the dictionary , the list of paths / keys and value , and return the modified dictionary.
probably means

def add_value(dict, path, value):
    -sharp dict
    -sharp path`["A", "B", "C"]`, ABBC
    -sharp value
    
    return dict

the function that needs to be implemented is something like this:

d = {}
add_value(d, ["A", "B", "C"], ("output.txt", "2mb"))
{"Aids: {" blockquote: {"output.txt",: [(" output.txt", "2mb")]}
add_value(d, ["X", "Y"], ("log.txt", "10kb"))
{"blockquote: {" string"}},"X": {"Yee: [(" log.txt", "10kb"),]}
add_value(d, ["A", "B", "C"], ("video.mp4", "2GB"))
{"Aids: {" log.txt",: {"blockquote: [(" output.txt", "2mb"), (" video.mp4", "2GB")]}}," X": {"Y": {"Zhe: [(" log.txt", "10kb"),]}
The length of

path is variable, or the depth of the directory is variable, so it seems to be called in a loop, not a few if structures.
A novice to python, I really don"t know how to achieve it. Ask for advice.

Feb.28,2021

if it is not for specific oj topics, it is recommended that xml, be more intuitive and easier to manage

from lxml import etree


def gen_xpath(path):
    return '//root/' + '/'.join(path)


def add_value(root, path, value):
    purpose_path = gen_xpath(path)
    folder = root.xpath(purpose_path)
    parent_folder = root
    if not folder:
        for i, name in enumerate(path, 1):
            temp_path = gen_xpath(path[:i])
            temp_folder = root.xpath(temp_path)
            if not temp_folder:
                parent_folder = etree.SubElement(parent_folder, name)
            else:
                parent_folder = temp_folder
    
    folder = root.xpath(purpose_path)[0]
    file = etree.SubElement(folder, 'file')
    file.set('name', value[0])
    file.set('size', value[1])


if __name__ == '__main__':
    root = etree.Element('root')
    add_value(root, ['A', 'B', 'C'], ('output.txt', '2mb'))
    add_value(root, ['X', 'Y'], ('log.txt', '10kb'))
    add_value(root, ['A', 'B', 'C'], ('video.mp4', '2GB'))
    etree.ElementTree(root).write('test.xml', pretty_print=True)

output result:

<root>
  <A>
    <B>
      <C>
        <file name="output.txt" size="2mb"/>
        <file name="video.mp4" size="2GB"/>
      </C>
    </B>
  </A>
  <X>
    <Y>
      <file name="log.txt" size="10kb"/>
    </Y>
  </X>
</root>

def add_value(dict_obj, path, value):
  obj = dict_obj
  for i ,v in enumerate(path):
    if i + 1 == len(path):
      if not isinstance(obj.get(v, ''), list):
        obj[v] = list()
      obj[v].append(value)
      continue
    obj[v] = obj.get(v, '') or dict()
    obj = obj[v]
  return dict_obj

d = {}
print add_value(d, ['A', 'B', 'C'], ('output.txt', '2mb'))
print add_value(d, ['X', 'Y'], ('log.txt', '10kb'))
print add_value(d, ['A', 'B', 'C'], ('video.mp4', '2GB'))
Menu