0

I'm trying to convert to floats the string values (which should have been represented as float originally) in the following dict:

{'a': '1.3', 'b': '4'}

If I try a dict comprehension:

{k:float(v) for v in d.values()}

I end up with just the second item in the dict:

In [191]: {k:float(v) for v in d.values()}
Out[191]: {'b': 4.0}

Why is this?

Pyderman
  • 14,809
  • 13
  • 61
  • 106

4 Answers4

6

Use d.items() and also you need to refer key,value separately through variables. Here k refers the key and v refers the value.

{k:float(v) for k,v in d.items()}

Example:

>>> d = {'a': '1.3', 'b': '4'}
>>> {k:float(v) for k,v in d.items()}
{'a': 1.3, 'b': 4.0}
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
6

The k value is not changed for every v value, change your code to below:

{k:float(v) for k, v in d.items()}
M.javid
  • 6,387
  • 3
  • 41
  • 56
3

Python dictionaries iteritems would be more appropriate solution.

{k:float(v) for k, v in d.iteritems()}

Also read dict.items() vs dict.iteritems()

Community
  • 1
  • 1
Tanveer Alam
  • 5,185
  • 4
  • 22
  • 43
3

Your k variable contains 'b' for some reason. Therefore your expression

{k:float(v) for v in d.values()}

is actually

{'b': float(v) for v in d.values()}

so the result is:

{'b': 4.0}
dlask
  • 8,776
  • 1
  • 26
  • 30