How to Create a Python Dictionary from Text File?
Last Updated :
23 Jul, 2025
The task of creating a Python dictionary from a text file involves reading its contents, extracting key-value pairs and storing them in a dictionary. Text files typically use delimiters like ':' or ',' to separate keys and values. By processing each line, splitting at the delimiter and removing extra spaces, we can efficiently construct a dictionary. For example, a file with name: Alice, age: 25, city: New York results in {'name': 'Alice', 'age': '25', 'city': 'New York'}.
Using dictionary comprehension
Dictionary comprehension is one of the most concise and optimized ways to transform a text file into a dictionary. It reads the file line by line, splits each line into a key-value pair and directly constructs the dictionary.
Python
# Create and write to input.txt
with open('input.txt', 'w') as f:
f.write("name: shakshi\nage: 23\ncountry: India")
# Read the file and create dictionary
with open('input.txt', 'r') as file:
res = {key.strip(): value.strip() for key, value in (line.split(':', 1) for line in file)}
print(res)
Output{'name': 'shakshi', 'age': '23', 'country': 'India'}
Explanation: This code writes key-value pairs to input.txt, then reads and processes it using dictionary comprehension. Each line is split at the first ':' and strip() removes extra spaces.
Using dict()
This approach directly constructs the dictionary using Python’s built-in dict() function with a generator expression. It is similar to dictionary comprehension but uses dict() explicitly.
Python
# Create and write to input.txt
with open('input.txt', 'w') as f:
f.write("name: shakshi\nage: 23\ncountry: India")
# Read the file and create dictionary
with open('input.txt', 'r') as file:
res = dict(line.strip().split(':', 1) for line in file)
print(res)
Output{'name': ' shakshi', 'age': ' 23', 'country': ' India'}
Explanation: This code creates input.txt in write mode, writes key-value pairs separated by ':', then reopens it in read mode. A dictionary comprehension processes each line by stripping spaces and splitting at the first ':' ensuring proper key-value separation.
Using csv.reader
csv.reader module is optimized for structured data and handles cases where values may contain colons (:). It ensures accurate parsing and avoids incorrect splits.
Python
import csv
# Create and write to input.txt
with open('input.txt', 'w') as f:
f.write("name: shakshi\nage: 23\ncountry: India")
# Read and process the file into a dictionary
with open('input.txt', 'r') as file:
reader = csv.reader(file, delimiter=':')
res = {row[0].strip(): row[1].strip() for row in reader if len(row) == 2}
print(res)
Output{'name': 'shakshi', 'age': '23', 'country': 'India'}
Explanation: This code writes key-value pairs to input.txt, then reads and processes it using csv.reader with ':' as the delimiter. It strips spaces and ensures valid key-value pairs before printing the dictionary.
Using for loop
A step-by-step approach using a loop gives explicit control over processing and is easier for beginners to understand.
Python
res = {} # initialize empty dictionary
# Create and write to input.txt
with open('input.txt', 'w') as f:
f.write("name: shakshi\nage: 23\ncountry: India")
# Read and process the file into a dictionary
with open('input.txt', 'r') as file:
for line in file:
key, value = line.strip().split(':', 1)
res[key.strip()] = value.strip()
print(res)
Output{'name': 'shakshi', 'age': '23', 'country': 'India'}
Explanation: This code writes key-value pairs to input.txt, then reads the file line by line. Each line is stripped of spaces, split at the first ':' and stored in the dictionary with cleaned key-value pairs.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice