I have a big file of text that is a list of dictionaries, like so
[{'a':'1', 'b':'2'},{'a':'3','b':'4'}]
How do i read this into python as a list of dictionaries?
I have a big file of text that is a list of dictionaries, like so
[{'a':'1', 'b':'2'},{'a':'3','b':'4'}]
How do i read this into python as a list of dictionaries?
You can also use ast.literal_eval
.
import ast
ast.literal_eval("[{'a':'1', 'b':'2'},{'a':'3','b':'4'}]")
Help on function literal_eval in module ast:
literal_eval(node_or_string) Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.
I learnt this trick at https://stackoverflow.com/a/21154138/1415639
You can use eval:
with open('filename') as f:
d = eval(f.read())
Bear in mind that eval
should be used with care, as mentioned in the comments, because you may end up executing harmful code if the input is not 100% in your control.