How to convert dict value to a float

33,287

Solution 1

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]))

Solution 2

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'>

Solution 3

if you have many values in a dictionary you can put all values in a list an after that take values, but you need also to change type because your values are of type strings not float

dict1= {'CNN': '0.000002'}
values = [float(x) for x in list(dict1.values())]

for value in values:
    print(value)

Solution 4

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'>
Share:
33,287
J87
Author by

J87

Updated on August 01, 2022

Comments

  • J87
    J87 almost 2 years

    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
    
  • Druta Ruslan
    Druta Ruslan about 6 years
    in his code value of CNN is '0.00002' of type string but in your code value of CNN is of type float
  • Shahebaz Mohammad
    Shahebaz Mohammad about 6 years
    Please read the lines before the code. I suggested modifying dictionary first and then expressed the results desired.
  • Druta Ruslan
    Druta Ruslan about 6 years
    ups, sorry, but if his dict come for example from http request ? how he will change it ?
  • J87
    J87 about 6 years
    Thanks, this one is working as float