13

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
jpp
  • 159,742
  • 34
  • 281
  • 339
J87
  • 179
  • 1
  • 1
  • 9
  • 1
    What's the result you want to get? A dict like `{'CNN': 0.00002}` or a single value like `s = 0.00002`? – Aran-Fey May 20 '18 at 10:20
  • 2
    Why are you using `values()` here? If you want to access the value of a single key, get it wth the square brackets syntax: `dict1["CNN"]`. – Daniel Roseman May 20 '18 at 10:21
  • what I want is s = 0.00002, dict key is not constant it could be CNN or something else. – J87 May 20 '18 at 10:24

4 Answers4

7

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'>
jpp
  • 159,742
  • 34
  • 281
  • 339
4

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]))
Paula Thomas
  • 1,152
  • 1
  • 8
  • 13
1

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)
Druta Ruslan
  • 7,171
  • 2
  • 28
  • 38
1

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