How to Create a Python Dictionary from Text File?
Last Updated :
26 Feb, 2024
Creating a Python dictionary from a text file involves reading the file content and structuring it into key-value pairs. Various methods such as open(), csv.reader, yaml, or other parsing techniques can be used to extract and organize the data from the text file into a dictionary format in Python. In this article, we will see how we can create a Python Dictionary from a text file in Python.
Create a Python Dictionary from a Text File in Python
Below are the ways to create a Python Dictionary From a Text File.
- Using open() and readlines() Functions
- Using csv.reader
- Using yaml module
input.txt
Python: Programming Language
Algorithms: Problem Solving
Data Structures: Collections
Web Development: Django, Flask
Create a Python Dictionary From Text File Using open() and readlines() Functions
In the below example, we read the text file “input.txt” using the open() and readlines() functions, extract the key-value pairs that are separated by colons, and create a dictionary named “res“. We are printing this created dictionary as output.
Python3
file = 'input.txt'
with open ( file , 'r' ) as file :
lines = file .readlines()
res = {}
for line in lines:
key, value = line.strip().split( ':' )
res[key.strip()] = value.strip()
print ( "Dictionary Created:" )
print (res)
|
Output:
Dictionary Created
{'Python': 'Programming Language', 'Algorithms': 'Problem Solving', 'Data Structures': 'Collections',
'Web Development': 'Django, Flask'}
Create a Python Dictionary From Text File Using csv.reader
In the below example, we use csv.reader module to read a text file named ‘input.txt’, where each line contains key-value pairs separated by colons. The code then creates a dictionary named ‘res‘ by iterating through the rows of the CSV data, stripping whitespace from keys and values, and finally prints the resulting dictionary.
Python3
import csv
file = 'input.txt'
with open ( file , 'r' ) as file :
reader = csv.reader( file , delimiter = ':' )
res = {row[ 0 ].strip(): row[ 1 ].strip() for row in reader}
print ( "Dictionary Created" )
print (res)
|
Output:
Dictionary Created
{'Python': 'Programming Language', 'Algorithms': 'Problem Solving', 'Data Structures': 'Collections',
'Web Development': 'Django, Flask'}
Create a Python Dictionary From Text File Using yaml module
In the below example, we use the yaml module to read a text file named ‘input.txt‘ in read mode. It then uses yaml.safe_load() to load the data from the YAML-formatted file, creating a dictionary named ‘res‘. The resulting dictionary is printed.
Python3
import yaml
file = 'input.txt'
with open ( file , 'r' ) as file :
res = yaml.safe_load( file )
print ( "Dictionary Created" )
print (res)
|
Output:
Dictionary Created
{'Python': 'Programming Language', 'Algorithms': 'Problem Solving', 'Data Structures': 'Collections',
'Web Development': 'Django, Flask'}
Share your thoughts in the comments
Please Login to comment...