Create a Nested Dictionary from Text File Using Python
Last Updated :
28 Apr, 2025
We are given a text file and our task is to create a nested dictionary using Python. In this article, we will see how we can create a nested dictionary from a text file in Python using different approaches.
Create a Nested Dictionary from Text File Using Python
Below are the ways to Create Nested Dictionary From Text File using Python:
- Using json.loads()
- Using Regular Expression
- Using eval()
input.txt
Name: "GeeksforGeeks"
Year: 2009
Topics: ["Algorithms", "Data Structures", "Python", "Java"]
Location: {"Country": "India", "City": "Noida"}
Create Nested Dictionary From Text File Using json.loads()
In this example, we are using the json.loads() method to create a nested dictionary from a text file in Python. The script reads each line from the file, checks for the presence of a colon to identify key-value pairs, and then uses json.loads() to convert the string representation of the value into a Python object, storing a nested dictionary named res with the extracted key-value pairs. Finally, the resulting nested dictionary is printed.
Python
import json
res = {}
with open('input.txt', 'r') as file:
for line in file:
if ':' in line:
key, value = line.strip().split(':', 1)
res[key] = json.loads(value)
print(res)
Output:
{'Name': 'GeeksforGeeks', 'Year': 2009, 'Topics': ['Algorithms', 'Data Structures', 'Python', 'Java'],
'Location': {'Country': 'India', 'City': 'Noida'}}
Create Nested Dictionary From Text File Using Regular Expression
In this example, we are using regular expressions (re.match()) to parse key-value pairs from each line of a text file and create a nested dictionary in Python. The regular expression \s*([^:]+)\s*:\s*(.+)\s* helps extract key and value components. The script checks for comma-separated values and splits them into a list when present, storing a nested dictionary named res with the extracted data. Finally, the resulting nested dictionary is printed.
Python3
import re
res = {}
with open('input.txt', 'r') as file:
for line in file:
match = re.match(r'\s*([^:]+)\s*:\s*(.+)\s*', line)
if match:
key, value = match.groups()
if ',' in value:
res[key] = value.split(',')
else:
res[key] = value
print(res)
Output:
{'Name': '"GeeksforGeeks"', 'Year': '2009', 'Topics': ['["Algorithms"', ' "Data Structures"', ' "Python"', ' "Java"]'],
'Location': ['{"Country": "India"', ' "City": "Noida"}']
Create Nested Dictionary From Text File Using eval()
In this example, we are using the eval() function to create a nested dictionary from a text file in Python. It reads each line from the file, identifies key-value pairs based on the presence of a colon, and applies eval() to interpret the value, converting it into a Python object, which is then stored in the nested dictionary named res.
Python3
res = {}
with open('input.txt', 'r') as file:
for line in file:
if ':' in line:
key, value = line.strip().split(':', 1)
res[key] = eval(value)
print(res)
Output:
{'Name': 'GeeksforGeeks', 'Year': 2009, 'Topics': ['Algorithms', 'Data Structures', 'Python', 'Java'],
'Location': {'Country': 'India', 'City': 'Noida'}}
Similar Reads
How to convert a MultiDict to nested dictionary using Python A MultiDict is a dictionary-like object that holds multiple values for the same key, making it a useful data structure for processing forms and query strings. It is a subclass of the Python built-in dictionary and behaves similarly. In some use cases, we may need to convert a MultiDict to a nested d
3 min read
How to Create a Dictionary in Python The task of creating a dictionary in Python involves storing key-value pairs in a structured and efficient manner, enabling quick lookups and modifications. A dictionary is an unordered, mutable data structure where each key must be unique and immutable, while values can be of any data type. For exa
3 min read
Write a dictionary to a file in Python A dictionary store data using key-value pairs. Our task is that we need to save a dictionary to a file so that we can use it later, even after the program is closed. However, a dictionary cannot be directly written to a file. It must first be changed into a format that a file can store and read late
3 min read
Ways to create a dictionary of Lists - Python A dictionary of lists is a type of dictionary where each value is a list. These dictionaries are commonly used when we need to associate multiple values with a single key.Initialize a Dictionary of ListsThis method involves manually defining a dictionary where each key is explicitly assigned a list
3 min read
Create Inverted Index for File using Python An inverted index is an index data structure storing a mapping from content, such as words or numbers, to its locations in a document or a set of documents. In simple words, it is a hashmap like data structure that directs you from a word to a document or a web page. Creating Inverted Index We will
3 min read
How to read Dictionary from File in Python? In Python, reading a dictionary from a file involves retrieving stored data and converting it back into a dictionary format. Depending on how the dictionary was savedâwhether as text, JSON, or binary-different methods can be used to read and reconstruct the dictionary for further use in your program
3 min read