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 a dict.
Replace ' ' with ',', append '{', and '}' to string and use eval() to get a dict.
So my question is which one is faster?
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With