First time here? Check out the FAQ!

Ask Your Question
0

Is it possible to convert a string to mapping?

asked 13 years ago

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
plt.hist(X,Y,**kwargs)

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.

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
1

answered 13 years ago

DSM gravatar image

updated 13 years ago

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.

Preview: (hide)
link

Comments

Thanks. that works!

Shashank gravatar imageShashank ( 13 years ago )

Your Answer

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

Add Answer

Question Tools

Stats

Asked: 13 years ago

Seen: 544 times

Last updated: Feb 02 '12