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.
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:
- 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:
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.
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:
- 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.
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:
- 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.