Open In App
Related Articles

Read List of Dictionaries from File in Python

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

A dictionary in Python is a collection where every value is mapped to a key. Since they are unordered and there is no constraint on the data type of values and keys stored in the dictionary, it is tricky to read dictionaries from files in Python.

Read a List of Dictionary from Text Files in Python

The problem statement mentions a list of dictionaries that have to be read from a file. We can read data from a text file as a string and convert that data into a dictionary in Python. Assuming our data is stored in a text file in the following format – 

{'geek': 10, 'geeky': True}
{'GeeksforGeeks': 'Education', 'geekgod': 101.0, 3: 'gfg'}
{'supergeek': 5}

The approach would include the following steps:

  • Open the text file in read mode and read the content
  • Parse every line in the content into a dictionary.

Reading using Pickle Module

The pickle module in Python is mostly used in fields like Data Science where data persistence is critical. The pickle module stores the given data as a serialized byte sequence into files that can be easily retrieved at a later time. Pickle module supports various Python objects and dictionaries are one among them. This method would include the following steps:

  • Importing the Pickle Module
  • Opening the file in read binary mode
  • Loading the data into a variable using the pickle module’s dump method
list_dictionary = pickle.load(filehandler)

Input file:

It uses the `pickle.load()` function to deserialize the data and store it in the variable `dictionary_list`. The code then iterates through each dictionary in the list and prints its contents. In case of any exceptions during file reading or unpickling, it catches the errors and prints a generic error message. It’s essential to ensure that “GFG.txt” contains valid pickled data created using `pickle.dump()` before running this code.

Python3

import pickle
 
 
try:
    geeky_file = open('GFG.txt', 'r')
    dictionary_list = pickle.load(geeky_file)
     
    for d in dictionary_list:
        print(d)
    geeky_file.close()
 
except:
    print("Something unexpected occurred!")

                    

Output:

Space Complexity: O(n) (where ‘n’ is the number of dictionaries in the list)
Time Complexity: O(max(m, n)) (where ‘m’ is the size of the data and ‘n’ is the number of dictionaries in the list)

Reading from Text File using read() Method

The read() method returns the specified number of bytes from the file. The default is -1 which means the whole file.

Input file:

It assumes the input string represents a dictionary-like structure, with key-value pairs separated by commas and enclosed within curly braces. The function processes each line of the “geeky_file.txt” file, calling `parse()` to convert each line into a dictionary and then prints the resulting dictionaries. If any errors occur during file reading, parsing, or printing, a generic error message is displayed. It is essential to ensure the file’s content adheres to the expected dictionary format for the code to work correctly.

Python3

def parse(d):
    dictionary = dict()
    # Removes curly braces and splits the pairs into a list
    pairs = d.strip('{}').split(', ')
    for i in pairs:
        pair = i.split(': ')
        # Other symbols from the key-value pair should be stripped.
        dictionary[pair[0].strip('\'\'\"\"')] = pair[1].strip('\'\'\"\"')
    return dictionary
try:
    geeky_file = open('geeky_file.txt', 'rt')
    lines = geeky_file.read().split('\n')
    for l in lines:
        if l != '':
            dictionary = parse(l)
            print(dictionary)
    geeky_file.close()
except:
    print("Something unexpected occurred!")

                    

Output:

Time complexity: O(n*m), where n is the number of lines in the file and m is the number of key-value pairs in each line.
Auxiliary space: O(m), where m is the maximum number of key-value pairs in a single line.



Last Updated : 31 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads