Convert String representation of a List to a Dictionary Python

  • A+
Category:Languages

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 :

{100:0.345,123:0.34,145:0.86} 

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] +"}") 

Comment

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