You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于AccuWeather API,如何在Python字典中同时填充城市英文名、天气文本及摄氏温度值

解决方法:将天气文本和温度整合到字典值中

你遇到的问题根源在于:原来的字典值是单个字符串(WeatherText),而append是列表专属的方法,字符串并没有这个功能,所以没法直接追加温度值。我们需要把每个城市对应的值改成能容纳多字段的容器结构,比如子字典或者元组,这样就能同时存储WeatherText和温度信息了。

推荐方案:用子字典存储多字段(可读性最强)

这种方式后续访问数据非常直观,代码修改如下:

weatherResponse = result.json()
mydictionary = {}  # 更简洁的字典初始化写法

for p in weatherResponse:
    english_name = p["EnglishName"]
    weather_text = p["WeatherText"]
    # 直接通过键取值比list.values()[0]更可靠,避免API响应结构变化导致的错误
    temp_c = p["Temperature"]["Metric"]["Value"]
    
    # 将当前城市的两个字段存入子字典,再关联到城市英文名的键上
    mydictionary[english_name] = {
        "WeatherText": weather_text,
        "Temperature (Celsius)": temp_c
    }
    
    # 打印验证结果
    print(f"City: {english_name}")
    print(f"Weather: {weather_text}")
    print(f"Temperature in Celsius: {temp_c}")
    print("--------")

访问数据示例

之后你可以通过键名快速获取目标信息:

# 获取Dhaka的温度
dhaka_temp = mydictionary["Dhaka"]["Temperature (Celsius)"]
# 获取Dhaka的天气文本
dhaka_weather = mydictionary["Dhaka"]["WeatherText"]

备选方案:用元组存储(更简洁)

如果不需要键名标识,只想快速存储两个值,也可以用元组:

mydictionary[english_name] = (weather_text, temp_c)

# 访问时通过索引取值
dhaka_weather = mydictionary["Dhaka"][0]
dhaka_temp = mydictionary["Dhaka"][1]

为什么append无效?

原来的代码中mydictionary[p["EnglishName"]] = p["WeatherText"]是把字符串赋值给字典的键,而字符串是不可变类型,根本没有append方法。只有列表、字典这类可变容器才有添加元素的相关方法,所以必须把值的类型改成容器类才能容纳多个字段。

内容的提问来源于stack exchange,提问作者Viol1997

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 17:42:40