我可以从网址中提取特定数据。
weather_data = r.get("http://api.openweathermap.org/data/2.5/weather?q=" + location)
json_weather = weather_data.text
weather_info = json.loads(json_weather)
print weather_info['coord']['lat']
print weather_info['coord']['lon']
问题是,如何提取多个数据并放入1个列表(dict)而不是逐个提取。
这是API
显示的内容{u'base': u'stations',
u'clouds': {u'all': 40},
u'cod': 200,
u'coord': {u'lat': 51.51, u'lon': -0.13},
u'dt': 1439476222,
u'id': 2643743,
u'main': {u'humidity': 88,
u'pressure': 1012,
u'temp': 291.71,
u'temp_max': 293.15,
u'temp_min': 290.15},
u'name': u'London',
u'rain': {u'1h': 1.78},
u'sys': {u'country': u'GB',
u'id': 5091,
u'message': 0.0242,
u'sunrise': 1439440988,
u'sunset': 1439493986,
u'type': 1},
u'visibility': 9000,
u'weather': [{u'description': u'light intensity shower rain',
u'icon': u'09d',
u'id': 520,
u'main': u'Rain'}],
u'wind': {u'deg': 60, u'speed': 4.6}}
预期的输出可能是这样的:
{'name' :London, 'country': GB, 'humidity' :88, 'lat' :51.51}
答案 0 :(得分:1)
您必须对每个索引使用字典理解,然后将所有内容合并回原始字典。像这样......
info = {key: val for key, val in weather_info.iteritems() if key in ['name']}
coord = {key: val for key, val in weather_info.get('coord', {}).iteritems() if key in ['lat']}
system = {key: val for key, val in weather_info.get('sys', {}).iteritems() if key in ['country']}
main = {key: val for key, val in weather_info.get('main', {}).iteritems() if key in ['humidity']}
info.update(coord)
info.update(system)
info.update(main)
print info
答案 1 :(得分:0)
由于您的键映射不准确,最简单的似乎是最好的。
summary = {}
summary["name"] = weather_info["name"]
summary["country"] = weather_info["sys"]["country"]
summary["humidity"] = weather_info["main"]["humidity"]
summary["lat"] = weather_info["coord"]["lat"]
print summary
>>> {'lat': 51.51, 'country': u'GB', 'name': u'London', 'humidity': 88}