Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whether eval() better than self-analysis?

Tags:

python

eval

Here is my situation, I have a string as follows

'a':1 'b':2 'c':3

I want to turn this to a dict, so I have two options:

  1. Split the string by ' ' and then by ':' then put the pairs to a dict.

  2. Replace ' ' with ',', append '{', and '}' to string and use eval() to get a dict.

So my question is which one is faster?

like image 268
Derrick Zhang Avatar asked Dec 02 '22 22:12

Derrick Zhang


1 Answers

I would do it like this:

import ast
result = ast.literal_eval(''.join(["{", s.replace(" ", ", "), "}"]))

You can also do this (although the difference may be negligible):

import ast
result = ast.literal_eval("{" + s.replace(" ", ", ") + "}")

It's better to use ast.literal_eval as it's safer for this purpose than using eval().

like image 134
Simeon Visser Avatar answered Dec 19 '22 22:12

Simeon Visser