Read List of Dictionaries from File in Python (original) (raw)

Last Updated : 4 Feb, 2026

Given a file containing a list of dictionaries, the task is to read all the dictionaries from the file and convert them back into Python dictionary objects. For example:

**Input (sample.txt)

{'name': 'geek'}
{'platform': 'GeeksforGeeks'}
{'active': False}

**Output

{'name': 'geek'}
{'platform': 'GeeksforGeeks'}
{'active': False}

To Download the sample file used in this article: click here

Below are different methods to read list of dictionaries from file.

Using ast.literal_eval()

ast.literal_eval() safely converts a string containing a Python literal (like a dictionary) into an actual Python object.

Python `

import ast

try: with open('data.txt', 'r') as file: for line in file: if line.strip():
dictionary = ast.literal_eval(line.strip()) print(dictionary) except Exception as e: print("Something unexpected occurred:", e)

`

**Output

{'name': 'geek', 'score': 10}
{'platform': 'GeeksforGeeks', 'rating': 4.8}
{'username': 'supergeek', 'active': False}

**Explanation:

Using Pickle Module

This method loads dictionaries from a file that was saved earlier using pickle.dump(). It is the safest and easiest way because pickle automatically converts the byte data back into Python objects.

To save the pickle file:

Python `

import pickle

data = [ {'name': 'geek', 'score': 10}, {'platform': 'GeeksforGeeks', 'rating': 4.8}, {'username': 'supergeek', 'active': False} ]

with open('data.pkl', 'wb') as file: pickle.dump(data, file)

`

The code saves a list of dictionaries into a binary file data.pkl using Pickle.

Python `

import pickle try: with open("data.pkl", "rb") as f: dict_list = pickle.load(f)

for d in dict_list:
    print(d)

except Exception as e: print("Error:", e)

`

**Output

{'name': 'geek', 'score': 10}
{'platform': 'GeeksforGeeks', 'rating': 4.8}
{'username': 'supergeek', 'active': False}

**Explanation:

Us**ing read() Method

This method treats each line in the file as a dictionary-like string and then manually converts it into a Python dictionary.

Python `

try: with open("file.txt", "r") as f: lines = f.readlines()

for l in lines:
    l = l.strip()
    if not l:
        continue

    d = {}
    for i in l.strip("{}").split(", "):
        k, v = i.split(":", 1)
        d[k.strip("'\" ").strip()] = v.strip("'\" ").strip()

    print(d)

except Exception as e: print("Error:", e)

`

**Output

{'name': 'geek', 'score': '10'}
{'platform': 'GeeksforGeeks', 'rating': '4.8'}
{'username': 'supergeek', 'active': 'False'}

**Explanation: