首页 > 解决方案 > 转换字典中的整数键值

问题描述

我的字典中有一个嵌套在 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)

标签: python

解决方案


您没有将值分配回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}

推荐阅读