Python - 如何更新多维dict

时间:2010-09-09 21:15:09

标签: python

跟进我之前的问题:Python - How to recursively add a folder's content in a dict

当我为每个文件和文件夹构建信息dict时,我需要将它合并到主树dict。到目前为止我找到的唯一方法是将dict写为文本字符串并将其解释为dict对象然后合并它。问题是根对象总是一样的,所以它被新的dict覆盖,我丢失了内容。

def recurseItem(Files, Item):
    global Settings
    ROOT = Settings['path']
    dbg(70, "Scanning " + Item)
    indices = path2indice(Item)
    ItemAnalysis = Analyse(Item)
    Treedict = ""#{'" + ROOT + "': "
    i=0
    for indice in indices:
        Treedict = Treedict + "{'" + indice + "': "
        i=i+1
    Treedict = Treedict + repr(ItemAnalysis)
    while i>0:
        Treedict = Treedict + "}"
        i=i-1
    Files = dict(Files.items() + Treedict.items())
return Files

有没有办法避免乱码索引构造(即文件[ROOT] [fileName] [fileName2] [fileName3] [fileName4])无法动态生成?我需要能够在不覆盖根密钥的情况下更新密钥的内容。任何想法都会受到欢迎!

2 个答案:

答案 0 :(得分:3)

当然,您可以即时创建嵌套字典。那怎么样:

# Example path, I guess something like this is produced by path2indice?!
indices = ("home", "username", "Desktop")

tree = {}

d = tree
for indice in indices[:-1]:
    if indice not in d:
        d[indice] = {}

    d = d[indice]

d[indices[-1]] = "some value"

print tree # this will print {'home': {'username': {'Desktop': 'some value'}}}

答案 1 :(得分:0)

我并不完全确定我理解你的要求,但它似乎是递归的教科书案例。我认为这样的东西可能有用(作为当前方法的替代品):

import os

FILES = ...
def process(directory):
    dir_dict = {}
    for file in os.listdir(directory):
        filename = os.path.join(directory, file)
        if os.path.isdir(file):
            dir_dict[file] = process(filename)
        else: # assuming it needs to be processed as a file
            dir_dict[file] = Analyse(filename)
    return dir_dict

(基于phihag's answer到你的另一个问题)基本上这会为每个目录构建一个dict,其中包含有关该目录中文件的分析信息,并将dict插入到父目录的dict中。

如果不是这样,我认为dict.update和/或collections.defaultdict类可能需要参与。