Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read the written list of dictionaries from file in Python

I have a file which is a list of dictionaries in this way:

[{'text': 'this is the text', 'filed1': 'something1', 'filed2': 'something2', 'subtexts': [{'body': 'body of subtext1', 'date': 'xx'}, {'body': 'body of subtext2', 'date': 'yy'}}]

The list of nested dictionaries and lists can have multiples dicts and lists inside. I want to read the file which is written exactly like this in python and create a data structure (list of dictionaries). How can it be done knowing it's not json but it has written to file by file.write(str(list)) where list is something we want to read back from file?

like image 855
Nick Avatar asked Apr 13 '16 17:04

Nick


People also ask

How do you print a dictionary list in Python?

So we have to get the dictionaries present in the list according to the key. We can get this by using dict. items().

How do I convert a list of dictionaries in Python?

Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.


1 Answers

Use ast.literal_eval which is a safe way of evaluating Python literals (as opposed to eval) into actual data structures.

That is:

import ast

with open('file.txt') as f:
    data = ast.literal_eval(f.read())

If you have something beyond the supported types (strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None), you can use my recipe in this answer.