To write a dictionary to a file in Python, there are a few ways you can do it depending on how you want the dictionary written.
If you want to write a dictionary just as you’d see it if you printed it to the console, you can convert the dictionary to a string and output it to a text file.
dictionary = {'name': "Bonnie", 'height':65}
with open('example.txt', 'w') as f:
f.write(str(dictionary))
This is the same as if you wanted to store the dictionary as JSON in a text file with the json.dumps().
import json
dictionary = {'name': "Bonnie", 'height':65}
with open('example.txt', 'w') as f:
f.write(json.dumps(dictionary))
If you want to write a dictionary as a comma delimited file with the keys and values in separate columns, you can do the following.
import json
dictionary = {'name': "Bonnie", 'height':65}
with open('example.csv', 'w') as f:
for k, v in dictionary.items():
f.write(str(k) + "," + str(v))
When working with data in your programs, the ability to easily be able to output to files in a readable way is valuable.
One such case is if you have a dictionary variable and you want to write to a file.
There are a few ways you can write a dictionary to a file depending on how you want the dictionary written.
To write a dictionary just as you’d see it if you printed it to the console, you can convert the dictionary to a string and output it to a text file.
Below shows you how you can simply write a dictionary to a file in Python.
dictionary = {'name': "Bonnie", 'height':65}
with open('example.txt', 'w') as f:
f.write(str(dictionary))
Writing Dictionary to File with json.dumps() in Python
If you want to write a dictionary to a file as JSON, then you can use the json module dumps() function.
dumps() converts dictionaries into JSON strings. If you write a dictionary to a file with json.dumps(), you can then load it with json.loads() at a later time.
Below shows you how to use the json module to write a dictionary to a file in Python.
import json
dictionary = {'name': "Bonnie", 'height':65}
with open('example.txt', 'w') as f:
f.write(json.dumps(dictionary))
Writing Dictionary Variable to .csv File in Python
One last way you can write a dictionary variable to a file is if you want to create a comma separated file with keys and values separated by commas.
To do this, you can use the dictionary items() function to get each key/value pair in the dictionary and write on their own line with a comma in between.
Below shows how you can make a csv file from a dictionary in Python.
import json
dictionary = {'name': "Bonnie", 'height':65}
with open('example.csv', 'w') as f:
f.write("key,value")
for k, v in dictionary.items():
f.write(str(k) + "," + str(v))
Hopefully this article has been useful for you to learn how to write dictionary variables to files in Python.