-1

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?

3 Answers3

4

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

Community
  • 1
  • 1
Fabio Montefuscolo
  • 2,258
  • 2
  • 21
  • 18
2

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.

eigil
  • 465
  • 10
  • 17
2

You can use literal_eval from ast which is a safer solution of eval. You can see why you shouldn't use eval here and here.

So what you want would be:

from ast import literal_eval


with open('file.txt') as f:
    dictionaries = literal_eval(f.read().strip()) 
Community
  • 1
  • 1
Stam Kaly
  • 668
  • 1
  • 11
  • 26