VOOZH about

URL: https://www.geeksforgeeks.org/python/read-list-of-dictionaries-from-file-in-python/

⇱ Read List of Dictionaries from File in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Read List of Dictionaries from File in Python

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.

Output

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

Explanation:

  • with open('data.txt', 'r') as file: Opens the file safely in read mode.
  • if line.strip(): Skips empty lines.
  • dictionary = ast.literal_eval(line.strip()): Converts line string to a Python dictionary safely.

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:

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

Output

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

Explanation:

  • import pickle: Loads the pickle module.
  • open("data.pkl", "rb"): Opens the pickle file in binary read mode.
  • pickle.load(f): Deserializes the file and returns the list of dictionaries.
  • for d in dict_list: Prints each dictionary in the list.

Using read() Method

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

Output

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

Explanation:

  • parse(line): Converts a dictionary-formatted string into a Python dictionary.
  • line.strip("{}"): Removes curly braces.
  • key, val = item.split(": "): Splits each pair.
  • f.read().split("\n"): Reads and splits file into lines.

Related Articles:

Comment