Save a dictionary to a file
Given a dictionary such as:
dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}
We can save it to one of these formats:
- Comma seperated value file (.csv)
- Json file (.json)
- Text file (.txt)
- Pickle file (.pkl)
You could also write to a SQLite database.
https://pythonspot.com/python-database-programming-sqlite-tutorial/
1. save dictionary as csv file
we can write it to a file with the csv module.
import csv
dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}
w = csv.writer(open("output.csv", "w"))
for key, val in dict.items():
w.writerow([key, val])
The dictionary file (csv) can be opened in Google Docs or Excel
2. save dictionary to json file
If you want to save a dictionary to a json file
import json
dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}
json = json.dumps(dict)
f = open("dict.json","w")
f.write(json)
f.close()
3. save dictionary to text file (raw, .txt)
You can save your dictionary to a text file using the code below:
dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}
f = open("dict.txt","w")
f.write( str(dict) )
f.close()
4. save dictionary to a pickle file (.pkl)
The pickle module may be used to save dictionaries (or other objects) to a file. The module can serialize and deserialize Python objects.
该模块可以序列化和反序列化 Python 对象。
serialize [ˈsɪərɪəlaɪz]:vt. 连载,使连续
deserialize:vt. 并行化,串并转换
import pickle
dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}
f = open("file.pkl","wb")
pickle.dump(dict,f)
f.close()