Open In App

Create a Nested Dictionary from Text File Using Python

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:



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.




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.




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.




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

Article Tags :