![]() |
VOOZH | about |
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.
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:
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:
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: