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:
-
Split the string by
' 'and then by':'then put the pairs to adict. -
Replace
' 'with',', append'{', and'}'to string and useeval()to get adict.
So my question is which one is faster?
I would do it like this:
You can also do this (although the difference may be negligible):
It’s better to use
ast.literal_evalas it’s safer for this purpose than usingeval().