首页 > 解决方案 > 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}]

这甚至可能吗?如果是这样,最好的方法是什么?

标签: pythonfiledictionary

解决方案


您可以使用该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}]

推荐阅读