Python dictionary allows you to store values in a key-value format.
You can save a dictionary to a file in Python using the json.dump(yourdict,fileobj) statement.
Basic Example
import json
json_filename = 'yourdict.csv'
yourdict = {'Name': 'Ram', 'Job': 'Expert', 'Salary': '90000'}
with open(json_filename, 'w') as f:
json.dump(yourdict,f)
Output
{"Name": "Ram", "Job": "Expert", "Salary": "90000"}
Let us learn how to write a dictionary in a different file format based on different use cases.
Table of Contents
Save Dictionary To Json File
JSON is a lightweight data-interchange format. You can use this format when you want to transfer data over a network.
To save a dictionary to a JSON file using the dump() method,
- Open a json file in a write mode. If the file doesn’t exist, the
open()
method will create it. - Use the
dump()
method to write the dictionary to the file object.
To learn more details about writing a dictionary to a JSON file, read: How To Dump A Dictionary Into A JSON File in Python
Code
import json
json_filename = 'yourdict.json’
yourdict = {'Name': 'Ram', 'Job': 'Expert', 'Salary': '90000'}
with open(json_filename, 'w') as f:
json.dump(yourdict,f)
Output
The JSON file will look like the one below.
{"Name": "Ram", "Job": "Expert", "Salary": "90000"}
Save Dictionary To CSV File
CSV is a comma-separated values file. It is easy to create and faster to handle.
To save a dictionary to a CSV file, use the csv.DictWriter.
- Open a CSV file in
write
mode. If the file doesn’t exist, theopen()
method will create it. - Create a
DictWriter
object with the file object, desired delimiter and fieldnames to use as a header. - Use the
writeheader()
method to write the header in the file. The keys in the dictionary will be written as headers. This is optional. - Use the
writerow()
method and pass the dictionary to write the values of the dictionary keys as data rows.
Code
import csv
csv_filename = 'yourdict.csv'
yourdict = {'Name': 'Ram', 'Job': 'Expert', 'Salary': '90000'}
with open(csv_filename, 'w') as f:
writer = csv.DictWriter(f, delimiter=',', fieldnames = ('Name', 'Job', 'Salary'))
#Optional
writer.writeheader()
writer.writerow(yourdict)
Output
Name,Job,Salary
Ram,Expert,90000
Save Dictionary To Text File
Text files are standard files, and they don’t contain any special formatting.
To save a dictionary to a text file, use the file.write() method.
- Open a text file in
write
mode. If the file doesn’t exist, theopen()
method will create it. - Open the file object using the file
open()
method. - Convert the dictionary to String and write it to the dictionary using the
write()
method.
Code
txt_filename = 'yourdict.txt'
yourdict = {'Name': 'Ram', 'Job': 'Expert', 'Salary': '90000'}
with open(txt_filename, 'w') as f :
f.write(str(yourdict))
Output
{'Name': 'Ram', 'Job': 'Expert', 'Salary': '90000'}
Saving Dictionary To File Using Pickle
Pickle files store python objects as a byte stream that can be stored in a database or transported data over a network.
In other words, this is also known as pickling or serialisation.
To save a dictionary to a pickle file, use the pickle.dump().
- Open a text file in
write
ANDbinary
mode usingwb
. If the file doesn’t exist, theopen()
method will create it. - Open the file object using the file
open()
method. - Dump the dictionary using the
pickle.dump()
method.
Code
import pickle
pickle_filename = 'yourdict.pkl'
yourdict = {'Name': 'Ram', 'Job': 'Expert', 'Salary': '90000'}
with open(pickle_filename, 'wb') as f:
pickle.dump(yourdict,f)
It is not possible to open the pickle file in the jupyter notebook. If you open it in any other editor, you’ll see the byte characters, and it is not a human-readable format.
Loop Through Dictionary And Write To File
This section demonstrates how to loop through the dictionary and write the contents to a file.
- Open the file in the append mode using
a
. - Use the
dict.items()
method and iterate over the dictionary items. It returns one key-value pair during each iteration. - Write the value to the file using the
file.write()
method.
Code
yourdict = {'Name': 'Ram', 'Job': 'Expert', 'Salary': '90000'}
txt2_filename = 'yourdict.txt'
with open(txt2_filename, 'a') as f:
for (key, val) in yourdict.items() :
itemstr = key +' : ' + val +'\n'
f.write(itemstr)
Output
Name : Ram
Job : Expert
Salary : 90000
Write Dictionary To File Line By Line
This section teaches you how to write a dictionary to a file line by line.
- Open the file in the append mode using
a
. - Use the
dict.items()
method and iterate over the dictionary items. It returns one key-value pair during each iteration. - Write the value to the file using the
file.write()
method. - each entry in the dictionary will be written as a new line in the file.
Code
yourdict = {'Name': 'Ram', 'Job': 'Expert', 'Salary': '90000'}
txt2_filename = 'yourdict.txt'
with open(txt2_filename, 'a') as f:
for (key, val) in yourdict.items() :
itemstr = key +' : ' + val +'\n'
f.write(itemstr)
Output
Name : Ram
Job : Expert
Salary : 90000