write Dictionary to file Python

How to write dictionary to file Python
How to write Dictionary to file Python

In this article, we will be solving a problem statement for how to write dictionary to file python. We will be discussing the steps and python methods required to solve this problem.

Dictionary is one of the data types present in Python. Python dictionary is an unordered collection of items. It is dynamic and mutable in nature. Each item of a dictionary is a key-value pair.

We can define a dictionary by enclosing a list of key-value pairs in curly brackets { }. The keys present in the dictionary must be unique.

Syntax:

dict_name = { key1 : value1 }

We can save dictionary to file in python in various ways. Below we have discussed some of the methods to write dictionary to file in python.

Method 1- Using json.dumps()

Python has an in-built package named as json to support JSON. The json package dumps() method is used to convert a Python object into a JSON string. To know about json package and method read here.

Steps to write dictionary in file using json.dumps:

  1. import json
  2. define the dictionary that you want to save in the file
  3. Open file in write mode
  4. Write dictionary using json.dumps()
  5. Close file

Python Code

# importing json library
import json

# defining the dictionary
records = { 
        "subject1" : 'python', 
        "subject2" : 'java', 
        "subject3" : 'ruby', 
        "subject4" : 'c++',
        "subject5" : 'c' 
        }

# Open file in write mode
file = open("mydict.txt", "w")

# write dictionary into file using json.dumps()
file.write(json.dumps(records))
file.close()

Output:

mydict.txt file image given below:

write dictionary to file output 1

Method 2- Using for loop and items()

The dictionary items() method returns an object which contains the list of key-value tuple pair.

Steps to write dictionary in file using for loop and items():

  1. define dictionary
  2. Open file in write mode
  3. Loop on the items of the dictionary which  we get from dictionary items() method
  4. Write the key and its corresponding value
  5. close the file

Using this method, you can write each key-value pair on the new line.

Python Code

# defining the dictionary
records = { 
        "subject1" : 'python', 
        "subject2" : 'java', 
        "subject3" : 'ruby', 
        "subject4" : 'c++',
        "subject5" : 'c' 
        }

# Open file in write mode
file = open("mydict.txt", "w")

for key,value in records.items():
  file.write(key + "\t" + value + "\n")
file.close()

Output:

mydict.txt file image given below:

write dictionary to file output 2

Method 3- using str() to write dictionary to file Python

In this method, we just convert the dictionary into a string and write that string into the file. To convert a dictionary to a string we use the str() function.

Python Code

# defining the dictionary
records = { 
        "subject1" : 'python', 
        "subject2" : 'java', 
        "subject3" : 'ruby', 
        "subject4" : 'c++',
        "subject5" : 'c' 
        }

# Open file in write mode
file = open("mydict.txt", "w")

# converting dictionary into string and writing into file
file.write(str(records))
file.close()

Output:

mydict.txt file image given below:

write dictionary to file output 1

Method 4- using keys() method

By using the keys() method of the dictionary we will get all the keys. We will iterate over the keys and write the key and its corresponding value to the file.

Python code:

# defining the dictionary
records = { 
        "subject1" : 'python', 
        "subject2" : 'java', 
        "subject3" : 'ruby', 
        "subject4" : 'c++',
        "subject5" : 'c' 
        }

# Open file in write binary mode
file = open("mydict.txt", "w")

# writing dictionary to file using keys()
for key in records.keys():
   file.write(key + "\t" + records[key] + "\n")
file.close()

Output:

mydict.txt file image given below:

write dictionary to file output 2

Method 5- using pickle.dump() to write dictionary to file Python

The Python Pickle module is used for serializing and de-serializing a Python object. The pickle module converts python objects like lists, dictionaries, etc into a character stream. To know about the Python Pickle module click here.

Since the Pickle module stores data in serialized byte sequence, open the file in wb mode i.e write binary mode and use the pickle module’s dump() method to write dictionary into the file.

Python Code

#importing pickle module
import pickle

# defining the dictionary
records = { 
        "subject1" : 'python', 
        "subject2" : 'java', 
        "subject3" : 'ruby', 
        "subject4" : 'c++',
        "subject5" : 'c' 
        }

# Open file in write binary mode
file = open("mydict.txt", "wb")

# writing dictionary to file using pickle.dump method
pickle.dump(records, file)
file.close()

Conclusion

In this article, we have seen 5 different ways to write dictionary to file python. We can write dictionary to file by using json.dumps, for loop with dictionary items(), str(), keys() and pickle.dump() method.