Write Dictionary to text file in Python

In this post, we will learn how to Write a Dictionary to a text file in Python by using different ways with code examples. Python dictionary is a data structure that stores data in key-value pairs.

1. Write dictionary to file using For loop


The simple method to write a dictionary to a text file is by using the ‘for’ loop. First Open the file in write mode by using the File open() method.

Then Get the key and value pair using the dictionary items() method from the Dictionary. Iterate over the key values of the dictionary using the ‘for’ loop and write key and value to a text file by using the write() method.

Program Example

dict_students = {'Name' : 'Jack', 'Sub' : 'Math', 'marks' : 100,'Grade':'A'}

file = open("DictFile.txt","w")

for key, value in dict_students.items(): 

 file.write('%s:%s\n' % (key, value))

file.close()

Output

It will create a file with the name (DictFile.txt) in the current directory and write the data as shown below.

Name:Jack
Sub:Math
marks:100
Grade:A

2. Pickle.dump() to write a dictionary to file


First, open the file in write mode by using “wb”, this mode is used to open files for writing in binary format. Use pickle.dump() to serialize dictionary data and then write to file.

To read a file we need to open the binary file in reading mode(“rb”), then use the pickle.load() method to deserialize the file contents. To check the output we are Printing the file contents using the print() method.

Program for Writing and Reading a dictionary to file

#python 3 program to write and read dictionary to text file 

import pickle
dict_students = {'Name' : 'Jack', 'Sub' : 'Math', 'marks' : 100,'Grade':'A'}
file = open("DictFile.pkl","wb")
pickle.dump(dict_students, file) 
file.close()

#reading the DictFile.pkl" contents
file = open("DictFile.pkl", "rb")
file_contents = pickle.load(file)
print(file_contents)

Output :

The file will get created in the current directory with the following data format.

{'Name': 'Jack', 'Sub': 'Math', 'marks': 100, 'Grade': 'A'}

3. JSON.dump() to write a dictionary to a text file


The JSON is a text format that is language-independent. It is very easy to read and write, the machine can easily parse it and generate it. We are using the JSON module dump() method.

  • Import the JSON Module.
  • open the file in write mode using with statement “with open(“DictFile.txt”,”w”) as file:”
  • Write the dictionary to file using write(json.dumps(dict_students)) method.

import json
dict_students = {'Name' : 'Jack', 'Sub' : 'Math', 'marks' : 100,'Grade':'A'}
with open("DictFile.txt","w") as file:
  file.write(json.dumps(dict_students)) 


#reading the json file
with open("DictFile.txt", "r") as file:
 file_content = file.read()
 print(file_content)

Output

{"Name": "Jack", "Sub": "Math", "marks": 100, "Grade": "A"}

4. Save dictionary to text with file.write()


In this example, we are saving a dictionary to a text file using the file.write() method.

Opening the file in write mode using the with statement. When using the with statement then there is no need to close the file. It is automatically handled by the compiler.

Then we are Writing the whole dictionary at one go by using the File. write() method. And using the str() method to convert a dictionary to string to write to file.

Program to save Dictionary to Text file

dict_students = {'Name' : 'Jack', 'Sub' : 'Math', 'marks' : 100,'Grade':'A'}

with open("DictFile.txt","w") as file:
  file.write(str(dict_students))

Output

{'Name': 'Jack', 'Sub': 'Math', 'marks': 100, 'Grade': 'A'}

5. Write dictionary to text file by dict.keys()


In this example, we are getting all dictionary keys by using the dictionary keys() method and iterating over all keys using for loop.

Writing key and values as a string by using this format “str(key)+” “+str(dict_students[key])” to file.We can change the format of the string as per requirement. Finally closing the file using the close() method.

dict_students = {'Name' : 'Jack', 'Sub' : 'Math', 'marks' : 100,'Grade':'A'}

 
  
file = open("dictfile.txt","w") 

for key in dict_students.keys(): 

   file.write(str(key)+"  "+str(dict_students[key])) 
   file.write("\n") 

file.close()

Output:

The file will get created with the following data in the current directory.

Name   Jack
Sub   Math
marks   100
Grade   A

Instead of keys(), we can use items() to write dictionary to file. Let us understand with an example

dict_students = {'Name' : 'Jack', 'Sub' : 'Math', 'marks' : 100,'Grade':'A'}

with open("Dictfile.txt","w") as file:
 for key,val in dict_students.items(): 
    string = str(key)+"   "+str(val)+"\n" 
    file.write(string) 

Output

Name   Jack
Sub   Math
marks   100
Grade   A

Summary

In this post, we have learned 5 different ways to Write Dictionary to a text file in Python with code examples.