python - 使用 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}
这部分通过返回一个字典来构建一个图。我想以相同的方式构建相同类型的图形(获取森林),但我想使用磁盘中的文件而不是将字典保存在内存中。有没有办法在文件中而不是在字典中构建森林?如果以后可以将文件的内容转储到字典中,那就太好了。
解决方案
这取决于森林中的所有值是否都是 json 可序列化的,您可以使用json.load
并json.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}
推荐阅读
- linux - 'arecord' 有效,但 FFMPEG '无法打开音频设备'
- python - 如何使用 Python 检查一年是否是闰年?
- apache-spark - PySpark MLLib 随机森林分类器可重复性问题
- amazon-web-services - 使用 NGINX 为网站的 QA 和 WWW 版本设置代理
- python - 如何在出现此错误的 vscode 中下载 python linter
- formatting - Qnx-neutrino 无法使用 fdisc 格式化我的分区,进程冻结
- r - 更改 R 图中图例的颜色
- android - Android 应用内购买:BillingClient:getPurchase() 失败。响应码:3
- jquery - 用于多项目显示的 Bootstrap 4 轮播包装问题
- php - 三叉树的深度 - 传销级别