A python dictionary is used to store key-value mappings in a program. Sometimes, we might need to store the dictionary directly in a file. In this article, we will discuss how we can save a dictionary directly to a file in Python.
Save Dictionary to File Using Strings in Python
To save a dictionary into a file, we can first convert the dictionary into a string. After that, we can save the string in a text file. For this, we will follow the following steps.
- First, we will convert the dictionary into a string using the str() function. The str() function takes an object as input and returns its string representation.
- After obtaining the string representation of the dictionary, we will open a text file in write mode using the open() function. The open() function takes the file name and the mode as input arguments and returns a file stream object say myFile.
- After obtaining the file stream object myFile, we will write the string to the text file using the write() method. The write() method, when invoked on a file object, takes a string as an input argument and writes it to the file.
- After execution of the write() method, we will close the file stream using the close() method.
By following the above steps, you can save a dictionary to a file in string form. After saving the dictionary to the file, you can verify the file content by opening the file. In the following code, we have first saved a python dictionary to a file.
myFile = open('sample.txt', 'w')
myDict = {'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
print("The dictionary is:")
print(myDict)
myFile.write(str(myDict))
myFile.close()
myFile = open('sample.txt', 'r')
print("The content of the file after saving the dictionary is:")
print(myFile.read())
Output:
The dictionary is:
{'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
The content of the file after saving the dictionary is:
{'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
Save Dictionary to File in Binary Format in Python
Instead of storing the dictionary in the text format, we can directly store the dictionary in the binary format. For this, we will use the pickle module in Python. To save the dictionary to file using the pickle module, we will follow the following steps.
- First, we will open a file in write binary (wb) mode using the open() function. The open() function takes the file name and the mode as input arguments and returns a file stream object say myFile.
- The pickle module provides us with the dump() method with the help of which, we can save a dictionary in binary format to the file. The dump() method takes an object as its first input argument and a file stream as the second input argument. After execution, it saves the object to the file in binary format. We will pass the dictionary as the first argument and myFile as the second input argument to the dump() method.
- After execution of the dump() method, we will close the file using the close() method.
Following is the python code to save a dictionary to a file in python.
import pickle
myFile = open('sample_file', 'wb')
myDict = {'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
print("The dictionary is:")
print(myDict)
pickle.dump(myDict,myFile)
myFile.close()
After saving the dictionary in the binary format, we can retrieve it using the load() method in the pickle module. The load() method takes the file stream containing the python object in binary form as its input argument and returns the Python object. After saving the dictionary to file using the dump() method, we can recreate the dictionary from the file as shown below.
import pickle
myFile = open('sample_file', 'wb')
myDict = {'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
print("The dictionary is:")
print(myDict)
pickle.dump(myDict,myFile)
myFile.close()
myFile = open('sample_file', 'rb')
print("The content of the file after saving the dictionary is:")
print(pickle.load(myFile))
Output:
The dictionary is:
{'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
The content of the file after saving the dictionary is:
{'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
Conclusion
In this article, we have discussed two ways to save a dictionary to a file in python. To know more about dictionaries, you can read this article on dictionary comprehension in python.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.