使用嵌套字典中的值填充Python字典

2024-06-26 02:45:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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函数,但不起作用

感谢您的帮助


Tags: nonefalsevalueunitmetrictempenprint
2条回答

您可以通过使用元组(如(a,b)添加多个值,而不是只向字典中添加一个值p[“WeatherText”]。请看下面的一行

mydictionary[p["EnglishName"]] = (p["WeatherText"], p["Temperature"]["Metric"]["Value"])

您可以使用上面这一行将多个值分配给字典键,示例输出如下:

{'Dhaka': ('Mostly cloudy', 32.2)}

您可以像读取列表一样读取元组

mydictionary["Dhaka"][0]          # This for getting the text 
mydictionary["Dhaka"][1]          # This for getting the value

此外,元组可能看起来类似于列表,但在这种情况下,建议使用元组,因为列表应存储相同的数据类型值,而元组可以存储多个数据类型值

I want to populate a dictionary with 1) "EnglishName", 2) "WeatherText", and 3) "Temperature (Celsius)". See below

data = [{
  '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'
}]

filtered_data = [{'EnglishName':e.get('EnglishName','NA'),'WeatherText':e.get('WeatherText','NA'),'temp_C':e.get('Temperature').get('Metric').get('Value')} for e in data]
print(filtered_data)

输出

[{'EnglishName': 'Dhaka', 'WeatherText': 'Mostly cloudy', 'temp_C': 32.2}]

相关问题 更多 >