我正在使用AccuWeather RESTFul API获取前50个城市的当前天气状况。JSON响应的一个对象如下所示:
{'Key': '28143', 'LocalizedName': 'Dhaka', 'EnglishName': 'Dhaka', 'Country': {'ID': 'BD', 'LocalizedName': 'Bangladesh', 'EnglishName': 'Bangladesh'}, 'TimeZone': {'Code': 'BDT', 'Name': 'Asia/Dhaka', 'GmtOffset': 6.0, 'IsDaylightSaving': False, 'NextOffsetChange': None}, 'GeoPosition': {'Latitude': 23.7098, 'Longitude': 90.40711, 'Elevation': {'Metric': {'Value': 5.0, 'Unit': 'm', 'UnitType': 5}, 'Imperial': {'Value': 16.0, 'Unit': 'ft', 'UnitType': 0}}}, 'LocalObservationDateTime': '2021-10-09T13:11:00+06:00', 'EpochTime': 1633763460, 'WeatherText': 'Mostly cloudy', 'WeatherIcon': 6, 'HasPrecipitation': False, 'PrecipitationType': None, 'IsDayTime': True, 'Temperature': {'Metric': {'Value': 32.2, 'Unit': 'C', 'UnitType': 17}, 'Imperial': {'Value': 90.0, 'Unit': 'F', 'UnitType': 18}}, 'MobileLink': 'http://www.accuweather.com/en/bd/dhaka/28143/current-weather/28143?lang=en-us', 'Link': 'http://www.accuweather.com/en/bd/dhaka/28143/current-weather/28143?lang=en-us'}
现在我想用1)“EnglishName”,2“WeatherText”和3“温度(摄氏度)”来填充字典
我确实设法获得了一个包含“EnglishName”和“WeatherText”的键值对,如下所示:
weatherResponse = result.json()
mydictionary = dict()
for p in weatherResponse:
print(p["EnglishName"])
print(p["LocalObservationDateTime"])
print(p["WeatherText"])
temp_C = list(p["Temperature"]["Metric"].values())[0]
print(f"Temperature in Celsius: {temp_C}")
print("--------")
mydictionary[p["EnglishName"]] = p["WeatherText"]
如何将每个键的“temp_C”值也分配给字典? 我尝试了append函数,但不起作用
感谢您的帮助
您可以通过使用元组(如(a,b)添加多个值,而不是只向字典中添加一个值p[“WeatherText”]。请看下面的一行
您可以使用上面这一行将多个值分配给字典键,示例输出如下:
您可以像读取列表一样读取元组
此外,元组可能看起来类似于列表,但在这种情况下,建议使用元组,因为列表应存储相同的数据类型值,而元组可以存储多个数据类型值
输出
相关问题 更多 >
编程相关推荐