Reputation: 450
I have an issue that really drives me mad. Normally doing int(20.0)
would result in 20
. So far so good. But:
levels = [int(gex_dict[i]) for i in sorted(gex_dict.keys())]
while gex_dict[i]
returns a float, e.g. 20.0
, results in:
"invalid literal for int() with base 10: '20.0'"
I am just one step away from munching the last piece of my keyboard.
Upvotes: 7
Views: 45500
Reputation: 4421
It looks like the problem is that gex_dict[i]
actually returns a string representation of a float '20.0'
. Although int() has the capability to cast from a float to an int, and a string representation of an integer to an int. It does not have the capability to cast from a string representation of a float to an int.
The documentation for int can be found here: http://docs.python.org/library/functions.html#int
Upvotes: 2
Reputation: 9511
The problem is that you have a string and not a float, see this as comparison:
>>> int(20.0)
20
>>> int('20.0')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '20.0'
You can workaround this problem by first converting to float and then to int:
>>> int(float('20.0'))
20
So it would be in your case:
levels = [int(float(gex_dict[i])) for i in sorted(gex_dict.keys())]
Upvotes: 1
Reputation: 7187
It looks like the value is a string, not a float. So you need int(float(gex_dict[i]))
Upvotes: 2
Reputation: 363487
'20.0'
is a string, not a float
; you can tell by the single-quotes in the error message. You can get an int
out of it by first parsing it with float
, then truncating it with int
:
>>> int(float('20.0'))
20
(Though maybe you'd want to store floats instead of strings in your dictionary, since that is what you seem to be expecting.)
Upvotes: 17