简体   繁体   中英

Python writing list of dictionaries

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?

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}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM