首页 > 解决方案 > 使用 Python 中的文件通过动态嵌套字典构建图形

问题描述

我使用以下代码构建了一个表示“森林”的大型嵌套字典,表示树的集合:

def create_forest(edges):
    """Given a list of edges [child, parent], return trees. """
    trees = collections.defaultdict(dict)
    for child, parent in edges:
        trees[parent][child] = trees[child]
    # Find roots
    children, parents = zip(*edges)
    roots = set(parents).difference(children)
    return {root: trees[root] for root in roots}

这部分通过返回一个字典来构建一个图。我想以相同的方式构建相同类型的图形(获取森林),但我想使用磁盘中的文件而不是将字典保存在内存中。有没有办法在文件中而不是在字典中构建森林?如果以后可以将文件的内容转储到字典中,那就太好了。

标签: pythonfiledictionarytree

解决方案


这取决于森林中的所有值是否都是 json 可序列化的,您可以使用json.loadjson.dump从文件中加载结构并将其转储到文件中,如下所示:

import json

forest = {
    "ancestro1": {
        "ancestor2":
            {
            "ancestror3": 123,
             "ancestor4":  654,
                "ancestor5": True}
    },
        "ancestor6":None
}


with open("file.json","w") as f:
    json.dump(forest,f)

with open("file.json","r") as f:
    forest = json.load(f)
print(forest)

输出:

{'ancestro1': {'ancestor2': {'ancestror3': 123, 'ancestor4': 654, 'ancestor5': True}}, 'ancestor6': None}

文件内容:

{"ancestro1": {"ancestor2": {"ancestror3": 123, "ancestor4": 654, "ancestor5": true}}, "ancestor6": null}


推荐阅读