Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert dict value to a float [duplicate]

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
like image 829
J87 Avatar asked May 20 '18 10:05

J87


3 Answers

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'>
like image 136
jpp Avatar answered Sep 17 '22 04:09

jpp


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]))
like image 22
Paula Thomas Avatar answered Sep 20 '22 04:09

Paula Thomas


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'>
like image 40
Shahebaz Mohammad Avatar answered Sep 21 '22 04:09

Shahebaz Mohammad