Ask Your Question

Is it possible to convert a string to mapping?

asked 2012-02-02 17:34:18 +0100

Shashank gravatar image

I am trying to develop a program which involves plotting. I am using matplotlib as a backend to plot histograms. In order to give the users more control over the plotting, I am trying to take a string from the users of the form

str = '\{\'alpha\':\'0.2\'\}'

and then passing is to a histogram using

kwargs = str

I get a error saying that kwargs must be a mapping not a string. Is there a way to convert a string to kwargs mapping? I am not trying to do this so that it works just for alhpa, but any option that hist accepts.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2012-02-02 18:36:40 +0100

DSM gravatar image

updated 2012-02-02 18:36:55 +0100

If the objects involved 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.

edit flag offensive delete link more


Thanks. that works!

Shashank gravatar imageShashank ( 2012-02-02 18:44:22 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2012-02-02 17:34:18 +0100

Seen: 430 times

Last updated: Feb 02 '12