0

How to convert this to a dictionary?

params = "{'cat_features':[X.columns.get_loc(i) for i in cat_vars], 
'num_boost_round':100, 'eta':.01, 'reg_lambda':1.8, 'verbose':False, 
'loss_function':'MultiClass','early_stopping_rounds':5}"

without the first part [X.columns.get_loc(i) for i in cat_vars] I can run ast.literal_eval(), but that doesn't work if there is python code in the string. Any idea how to solve this?

5
  • 1
    Can you trust the contents of the string? Commented Feb 7, 2019 at 21:45
  • 1
    You can use the eval function instead, if you are sure that X.columns.get_loc(i) has no dependencies on external data source; otherwise the use of eval would introduce security risks. Commented Feb 7, 2019 at 21:45
  • 2
    But you want to execute the code inside or skip it? Commented Feb 7, 2019 at 21:47
  • This screams X-Y problem. Why are you dynamically executing a string as python code? Why not create a function and call that function? Commented Feb 7, 2019 at 22:14
  • This is reading a dictionary from a config file. By default the values are read as strings. I need to convert the string into an evaluation... and yes... i can trust the contents of the string but that's not what I asked. Commented Feb 7, 2019 at 23:58

1 Answer 1

3

You can use plain eval.

However, using eval is is risky if the string comes from an non-trusted source because a properly crafted string could execute anything on the computer where the program is running.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.