Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a comma separated string of key values pairs to dictionary

I need to convert a comma separated string with key value pairs separated by colon into a dictionary where value is expected to be a float. I'm able to do this to get a dict:

>>> s = 'us:0.9,can:1.2,mex:0.45'
>>> dict(x.split(':') for x in s.split(','))

which results in:

{'us': '0.9', 'can': '1.2', 'mex': '0.45'}

but not sure how to force the value to be not a string ie, I'm expecting this:

{'us': 0.9, 'can': 1.2, 'mex': 0.45}

How to force the values to be floats?

Thanks!

like image 981
user2727704 Avatar asked Dec 03 '22 19:12

user2727704


1 Answers

How about:

{k: float(v) for k, v in [i.split(':') for i in s.split(',')]}
like image 84
g.d.d.c Avatar answered Feb 08 '23 23:02

g.d.d.c