Reputation: 906
What's the best way to write a list of dictionaries to a file in python?
d1 = {"apple": 3}
d2 = {"banana": 1}
data = []
data.append(dict(d1))
data.append(dict(d2)) #data is now [{"apple": 3}, {"banana": 1}]
I want to write that list to a file and also read the list and eventually add another dictionaries
Something like:
f = open(..)
l = f.read()
and now l
is a list of dictionaries that I can manipulate
Also adding dictionaries to the list like
d3 = {"orange": 1}
f.write(d3)
And now the file contains [{"apple": 3}, {"banana": 1}, {"orange": 1}]
Is this even possible? If so, what's the best approach?
Upvotes: 1
Views: 78
Reputation: 4680
You could use the json
module:
>>> import json
>>> with open("sample.txt", "w") as file:
json.dump(data, file)
And to read the file:
>>> with open("sample.txt", "r") as file:
data = json.load(file)
>>> data
[{'apple': 3}, {'banana': 1}]
Upvotes: 3