python - Python写字典列表
问题描述
将字典列表写入python文件的最佳方法是什么?
d1 = {"apple": 3}
d2 = {"banana": 1}
data = []
data.append(dict(d1))
data.append(dict(d2)) #data is now [{"apple": 3}, {"banana": 1}]
我想将该列表写入文件并读取该列表并最终添加另一个字典
类似于:
f = open(..)
l = f.read()
现在l
是我可以操作的字典列表
还将字典添加到列表中,例如
d3 = {"orange": 1}
f.write(d3)
现在文件包含[{"apple": 3}, {"banana": 1}, {"orange": 1}]
这甚至可能吗?如果是这样,最好的方法是什么?
解决方案
您可以使用该json
模块:
>>> import json
>>> with open("sample.txt", "w") as file:
json.dump(data, file)
并读取文件:
>>> with open("sample.txt", "r") as file:
data = json.load(file)
>>> data
[{'apple': 3}, {'banana': 1}]
推荐阅读
- python - python中与pc交互(鼠标+截图)
- java - Kafka:禁用从 Java 创建主题
- python - Python select() 消耗 100% CPU
- java - Java比较arraylist中数组的元素
- javascript - 无法将值添加到列表 c# mvc asp.net
- r - 用闰年计算一年中的天数
- linq - 使用 MOQ linq 模拟 void 方法来模拟功能语法
- primefaces - primefaces 反转列显示顺序
- firebase - BigQuery - Firebase Analytics 与 Firebase Crashlytics
- python - 如何防止循环堆栈中的重复值?