Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

If the keys involved are strings and the values are built-in Python types, you can use literal_eval:

sage: import ast 
sage: s = "{'alpha': 0.2}"
sage: type(s)
<type 'str'>
sage: m = ast.literal_eval(s)
sage: m
{'alpha': 0.20000000000000001}
sage: type(m)
<type 'dict'>

literal_eval is safe and doesn't allow for arbitrary code execution. eval and sage_eval both will, which is always a bit dangerous.

BTW, you should try to avoid calling variables str -- that clobbers the built-in str type.

If the keys objects involved are strings and the values are built-in Python types, you can use literal_eval:

sage: import ast 
sage: s = "{'alpha': 0.2}"
sage: type(s)
<type 'str'>
sage: m = ast.literal_eval(s)
sage: m
{'alpha': 0.20000000000000001}
sage: type(m)
<type 'dict'>

literal_eval is safe and doesn't allow for arbitrary code execution. eval and sage_eval both will, which is always a bit dangerous.

BTW, you should try to avoid calling variables str -- that clobbers the built-in str type.