Piy*_*kar 0 python string dictionary list
我有一个看起来像的字符串.
"[{'P_Key': 'val1', 'Price': '3.95'}, {'P_Key': 'val2', 'Price': '2.2'}, {'P_Key': 'val3', 'Price': '0.4'}]"
Run Code Online (Sandbox Code Playgroud)
我想将其转换为字典列表,如:
[{'P_Key': 'val1', 'Price': '3.95'},
{'P_Key': 'val2', 'Price': '2.2'},
{'P_Key': 'val3', 'Price': '0.4'}]
Run Code Online (Sandbox Code Playgroud)
字符串中可能有任意数量的此类字典.
这比eval只评估有效的python数据类型更安全
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'}]
Run Code Online (Sandbox Code Playgroud)