Python - 如何更新多维字典
这是我之前问题的后续:Python - 如何递归地将文件夹的内容添加到字典中。
当我为每个文件和文件夹构建信息字典时,我需要把它合并到主树字典中。到目前为止,我找到的唯一方法是把字典写成文本字符串,然后将其转换回字典对象,再进行合并。问题是根对象总是相同的,所以新的字典会覆盖掉旧的字典,这样我就丢失了内容。
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
有没有办法避免那种复杂的索引结构(比如 Files[ROOT][fileName][fileName2][fileName3][fileName4]),这种结构不能动态生成?我需要能够更新某个键的内容,而不覆盖根键。任何建议都非常欢迎!
2 个回答
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在你另一个问题中的回答)基本上,这个方法会为每个目录构建一个字典,里面包含了该目录下文件的分析信息,然后把这个字典放到父目录的字典里。
如果不是这个方法,我觉得可能需要用到dict.update
和/或collections.defaultdict
这个类。
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'}}}