Convert a comma separated string of key values pairs to dictionary

Viewed 4301

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!

5 Answers

How about:

{k: float(v) for k, v in [i.split(':') for i in s.split(',')]}

Maybe it can be confusing but you can try this :

s = 'us:0.9,can:1.2,mex:0.45'

dict((a, float(b)) for a,b in [x.split(':') for x in s.split(',')])

The output :

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

You can define a function for this:

s = 'us:0.9,can:1.2,mex:0.45'

def key_val_split(L):
    key, val = L.split(':')
    return key, float(val)

res = dict(key_val_split(x) for x in s.split(','))

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

Try this:

s = 'us:0.9,can:1.2,mex:0.45'
t = {k:float(v) for k, v in dict(x.split(':') for x in s.split(',')).items()}
print(t)

Output is:

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

Playing around with 3rd party Pandas, you can do quite a bit with pd.read_csv:

import pandas as pd

s = 'us:0.9,can:1.2,mex:0.45'

d = pd.read_csv(pd.compat.StringIO(s), sep=':', header=None, lineterminator=',')\
      .set_index(0)[1].to_dict()

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