如何将字典值转换为浮点数

J87*_*J87 6 python dictionary python-2.7 python-3.x

如何将字典值转换为浮点数

dict1= {'CNN': '0.000002'}

s=dict1.values()
print (s)
print (type(s))
Run Code Online (Sandbox Code Playgroud)

我得到的是:

dict_values(['0.000002'])
<class 'dict_values'> # type, but need it to be float
Run Code Online (Sandbox Code Playgroud)

但是我想要的是float值,如下所示:

 0.000002
 <class 'float'> # needed type
Run Code Online (Sandbox Code Playgroud)

jpp*_*jpp 7

要修改现有字典,您可以迭代视图并通过循环更改值的类型for

这可能是比float每次检索值时都转换为更合适的解决方案。

dict1 = {'CNN': '0.000002'}

for k, v in dict1.items():
    dict1[k] = float(v)

print(type(dict1['CNN']))

<class 'float'>
Run Code Online (Sandbox Code Playgroud)


Pau*_*mas 5

这里有两件事:首先 s 实际上是字典值的迭代器,而不是值本身。其次,一旦您提取了值,例如通过 for 循环。好消息是您只需一行即可完成此操作:

print(float([x for x in s][0]))
Run Code Online (Sandbox Code Playgroud)