2 Ways to Convert a text file to a dictionary in Python

Dictionary

In this article, we are going to learn about How to Convert a text file to a 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

So to start with, Let us Assume, we have the following text file (lang.txt) which contains the following data.

File content

1 C++
2 Python
3 java
4 GO
5 Rust
6 Javascript
7 C#

Python Program

Consider the example below to convert the data content to a 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#'}

How does it work

Now let us jump into the details of the program and learn each step with the explanation. To start with the process 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.

dictionary = {}

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.

with open("lang.txt") as file:

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 creating the dictionary items, this will keep going until we reach the end of the file.

2. Convert Text file to Dictionary

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 understand with 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'}

Conclusion :

We have explored 2 Ways to Convert a text file to a 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 requirement.