0

I have a string which looks like.

"[{'P_Key': 'val1', 'Price': '3.95'}, {'P_Key': 'val2', 'Price': '2.2'}, {'P_Key': 'val3', 'Price': '0.4'}]"

I want to convert this into a list of dictionaries like:

[{'P_Key': 'val1', 'Price': '3.95'}, 
 {'P_Key': 'val2', 'Price': '2.2'}, 
 {'P_Key': 'val3', 'Price': '0.4'}]

There may be any number of such dictionaries in the string.

Ma0
  • 14,712
  • 2
  • 33
  • 62

2 Answers2

5

use ast.literal_eval

this is safer compare to eval as it only evaluate valid python datatypes

s = "[{'P_Key': 'val1', 'Price': '3.95'}, {'P_Key': 'val2', 'Price': '2.2'}, {'P_Key': 'val3', 'Price': '0.4'}]"
import ast
ast.literal_eval(s)
# [{'P_Key': 'val1', 'Price': '3.95'}, {'P_Key': 'val2', 'Price': '2.2'}, {'P_Key': 'val3', 'Price': '0.4'}]
Skycc
  • 3,405
  • 1
  • 9
  • 17
0

use eval

 eval("[{'P_Key': 'val1', 'Price': '3.95'}, {'P_Key': 'val2', 'Price': '2.2'}, {'P_Key': 'val3', 'Price': '0.4'}]")
Abhishek Bhatia
  • 718
  • 7
  • 26