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
  • 15,057
  • 4
  • 35
  • 65

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,496
  • 1
  • 12
  • 18
0

use eval

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