Convert String representation of a List to a Dictionary Python

  • A+

How can I convert a str representation of the list, such as the below string into a dictionary?

a = '[100:0.345,123:0.34,145:0.86]' 

Expected output :


First tried to convert the string into a list using ast.literal_eval. But it's showing an error as : invalid syntax


It's showing as invalid syntax because it has the wrong brackets, so you could do

ast.literal_eval(a.replace("[","{").replace("]", "}")) 

Or alternatively parse the string yourself in a dictionary comprehension

{x.split(":")[0]: x.split(":")[1] for x in a[1:-1].split(",")} 

and if as mentioned there are [ or ] elsewhere in your string the following may be more robust

ast.literal_eval("{" + a[1:-1] +"}") 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: