python - 转换字典中的整数键值
问题描述
我的字典中有一个嵌套在 Python 列表中的数据,如下所示。我想要做的是将一些整数值从摄氏度转换为华氏度,但我知道我在尝试保存转换后的温度值时做错了。
data = [{'gas_station/headquarters/12032/Space Temperature Local': 21.368864059448242,
'gas_station/headquarters/12033/Space Temperature Local': 22.3087215423584,
'gas_station/headquarters/31/ZN-T': 71.94377136230469,
'gas_station/headquarters/29/ZN-T': 72.39180755615234,
'gas_station/headquarters/12028/Space Temperature Local': 22.77256202697754,
'gas_station/headquarters/27/ZN-T': 71.6547622680664,
'gas_station/headquarters/30/ZN-T': 69.44559478759766,
'gas_station/headquarters/26/ZN-T': 71.9398422241211},
{}]
for key, value in data[0].items():
if value < 40:
#print(key, value)
print(f'*** [INFO] *** - Celsius found values on {key} is {value}')
value = (9/5) * value + 32
print(f'*** [INFO] *** - New converted temp is {value}')
我在将新转换的摄氏度到华氏度温度数据保存到原始列表/字典数据类型时做错了。有人有什么建议吗?如果我再次打印data
原始温度单位,则存在原始温度单位。
for key, value in data[0].items():
print(key, value)
解决方案
您没有将值分配回dict
. 如果您想坚持您的循环,请执行以下操作:
data[0][key] = (9/5) * value + 32
另外,您可以考虑使用 dict 理解而不是循环
data[0] = {key: (9/5)*value+32 if value<40 else value for key,value in data[0].items()}
>>> data[0]
{'gas_station/headquarters/12032/Space Temperature Local': 70.46395530700684,
'gas_station/headquarters/12033/Space Temperature Local': 72.15569877624512,
'gas_station/headquarters/31/ZN-T': 71.94377136230469,
'gas_station/headquarters/29/ZN-T': 72.39180755615234,
'gas_station/headquarters/12028/Space Temperature Local': 72.99061164855956,
'gas_station/headquarters/27/ZN-T': 71.6547622680664,
'gas_station/headquarters/30/ZN-T': 69.44559478759766,
'gas_station/headquarters/26/ZN-T': 71.9398422241211}
推荐阅读
- php - PHP curl Connection timed out error
- android - 数据与服务器同步到房间数据库
- java - 为什么我们不能手动遍历 LinkedList?
- makefile - 为 pdftohtml 制作链接器会导致编译器错误
- laravel - Laravel 5 GET api 调用正在工作,但 POST api 调用不起作用
- javascript - JS - 如何通过 Promise.All 从已解决的 promes 中获取价值
- ibm-mobilefirst - 是否有可能访问 UserAuthenticationSecurityCheck 扩展类中的 ConfigurationAPI
- jquery - 从数据表导出时防止每列的隐藏内容
- c# - RabbitMq 以异步方式处理接收到的消息
- sql - 即使使用 NVARCHAR(MAX),动态 SQL 查询也不能存储超过 4000 个字符