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
  • 12,579
  • 12
  • 54
  • 98

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
  • 166,785
  • 24
  • 204
  • 249
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
  • 5,881
  • 3
  • 38
  • 54
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
  • 4,987
  • 3
  • 20
  • 41
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,280
  • 1
  • 24
  • 29