How to convert dict value to a float
dict1= {'CNN': '0.000002'}
s=dict1.values()
print (s)
print (type(s))
What I am getting is:
dict_values(['0.000002'])
<class 'dict_values'> # type, but need it to be float
but what I want is the float value as below:
0.000002
<class 'float'> # needed type
To modify your existing dictionary, you can iterate over a view and change the type of your values via a for
loop.
This may be a more appropriate solution than converting to float
each time you retrieve a value.
dict1 = {'CNN': '0.000002'}
for k, v in dict1.items():
dict1[k] = float(v)
print(type(dict1['CNN']))
<class 'float'>
Two things here: firstly s is, in effect, an iterator over the dictionary values, not the values themselves. Secondly, once you have extracted the value, e.g. by a for loop.The good news is you can do this is one line:
print(float([x for x in s][0]))
You have stored the number as in a string. The use of quotes dict1= {'CNN': '0.000002'}
makes it a string. Instead, assign it `dict1= {'CNN': 0.000002}
Code:
dict1= {'CNN': 0.000002}
s=dict1.values()
print (type(s))
for i in dict1.values():
print (type(i))
Output:
<class 'dict_values'>
<class 'float'>
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