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?
So we have to get the dictionaries present in the list according to the key. We can get this by using dict. items().
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With