gpt4 book ai didi

Python - 如何更新多维字典

转载 作者:太空宇宙 更新时间:2023-11-04 01:42:21 26 4
gpt4 key购买 nike

跟进我之前的问题:Python - How to recursively add a folder's content in a 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

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

最佳答案

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

# 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'}}}

关于Python - 如何更新多维字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3680635/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com