In this article, we are going to learn about 4 Ways to Convert text file to dictionary in Python. This is a very helpful exercise for programmers who works with data files. As a Data Analyst or Data scientist when we have huge data in files then we need to convert that data into python objects. This conversion helps us in handling the data in an organized manner.
We will learn about one of the use cases where we will be converting the text file data to a Python dictionary object. To understand this, We will take a sample text file and will read the content, and load it in the Python dictionary.
1. Convert a text file to a dictionary in Python using For loop
How does it work
- First, we will create an empty dictionary that will hold the file data in the form of dictionary data. Then we will open the file ‘lang.txt’ to start reading the content of the file.
- Now we have the file open and next we will read the data line by line from this file. Once we read each line then we will use the split function to split the line contents.
The line content is then assigned to the key and value pair of the dictionary. Since we are using the for loop to iterate the lines of a file and then create the dictionary items, this will keep going until we reach the end of the file. Consider the example below to convert the data content to a dictionary.
dictionary = {}
with open("lang.txt") as file:
So to start with, Let us Assume, we have the following text file (lang.txt) which contains the following data.
File content in the below program
1 C++
2 Python
3 java
4 GO
5 Rust
6 Javascript
7 C#
Python Program how to convert text file into Dictionary
#an empty dictionary
dictionary = {}
with open("lang.txt") as file:
for line in file:
(key, value) = line.split()
dictionary[int(key)] = value
print ('\ntext file to dictionary=\n',dictionary)
Output
text file to dictionary=
{1: 'C++', 2: 'Python', 3: 'java', 4: 'GO', 5: 'Rust', 6: 'Javascript', 7: 'C#'}
Most Popular Post
- Append Value To An Existing Key of Python Dictionary
- How to check Mutiple key exist in Python dictionary
- Filter A List Of Python Dictionaries By Conditions
- Extract Multiple keys value from a Python dictionary
- Write Dictionary to text file in Python
- Extract Multiple keys value from a Python dictionary
- How to swap key-value in Python Dictionary
2. Convert Text file to Dictionary in Python using strip()
In this way, we are now able to convert the file content to a dictionary. We can print the dictionary to confirm the desired results are there. So to start with, Let us Assume, we have the following text file (data.txt) which contains the following data.
myline = data
myline2 = This is data
myline3 = Dict_Keydata
myline4 = Dict_datavalue
Let’s understand with an example how to convert this text file into a dictionary
myfile = open("data.txt", 'r')
data_dict = {}
for line in myfile:
k, v = line.strip().split('=')
data_dict[k.strip()] = v.strip()
myfile.close()
print(' text file to dictionary =\n ',data_dict)
We will get this output:
text file to dictionary =
{'myline': 'data', 'myline2': 'This is data', 'myline3': 'Dict_Keydata', 'myline4': 'Dict_datavalue'}
3. JSON Module to Convert text file to dictionary in Python
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.
For Convert text file to Dict
- open the file in read mode using with the statement “with open(“DictFile.txt”,”r”) as file:”
- Convert text file to Dictionary using file_content = file.read()
- Print file contents using the print 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 contents:',file_content)
Output
file contents: {"Name": "Jack", "Sub": "Math", "marks": 100, "Grade": "A"}
4. Pickle. dump() to Convert dictionary to a text file in
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'}
Conclusion :
We have explored 4 Ways to Convert text file to dictionary in Python. In a second way, we are using the delimiter to separate the key-value pair. We can do any of these two ways as per our requirements.