How to Create a Python Dictionary from Text File?
Last Updated :
13 Feb, 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.
Similar Reads
Create Dictionary from the List-Python The task of creating a dictionary from a list in Python involves mapping each element to a uniquely generated key, enabling structured data storage and quick lookups. For example, given a = ["gfg", "is", "best"] and prefix k = "def_key_", the goal is to generate {'def_key_gfg': 'gfg', 'def_key_is':
3 min read
Create Dictionary Of Tuples - Python The task of creating a dictionary of tuples in Python involves mapping each key to a tuple of values, enabling structured data storage and quick lookups. For example, given a list of names like ["Bobby", "Ojaswi"] and their corresponding favorite foods as tuples [("chapathi", "roti"), ("Paraota", "I
3 min read
Python program to read character by character from a file Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file character by character. In this article, we will cover a few examples of it.ExampleInput: GeeksOutput: G e e k sExplanation: Iterated through character by character
2 min read
Create a Dictionary from a String The task of creating a dictionary from a string in Python often involves converting a string representation of a dictionary into an actual Python dictionary.For example, a string like "{'A':13, 'B':14, 'C':15}" represents a dictionary with keys 'A', 'B', and 'C' mapped to their respective values. Th
3 min read
Python program to convert XML to Dictionary In this article, we will discuss how to convert an XML to a dictionary using Python.Modules Usedxmltodict: It is a Python module that makes working with XML feel like you are working with [JSON]. Run the following command in the terminal to install the module.Syntax:pip install xmltodictpprint: The
2 min read
How to Add User Input To A Dictionary - Python The task of adding user input to a dictionary in Python involves taking dynamic data from the user and storing it in a dictionary as key-value pairs. Since dictionaries preserve the order of insertion, we can easily add new entries based on user input.For instance, if a user inputs "name" as the key
3 min read