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!
How about:
{k: float(v) for k, v in [i.split(':') for i in s.split(',')]}
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