繁体   English   中英

在python中将数据用于'requests'模块

[英]Using the data for 'requests' module in python

我可以使用以下代码从python的请求模块中加载一些天气数据:

 from pprint import pprint
import requests

r = requests.get('http://api.openweathermap.org/data/2.5/weather?q=London')

pprint(r.json())

但是我实际上如何使用它产生的数据? 我一生无法找到有关如何执行此操作的相关文档或教程。 这是pprint的输出:

{u'base': u'cmc stations',
 u'clouds': {u'all': 0},
 u'cod': 200,
 u'coord': {u'lat': 42.98, u'lon': -81.23},
 u'dt': 1397676977,
 u'id': 6058560,
 u'main': {u'humidity': 25,
           u'pressure': 1024,
           u'temp': 278,
           u'temp_max': 283.15,
           u'temp_min': 275.37},
 u'name': u'London',
 u'rain': {u'1h': 0.25},
 u'snow': {u'3h': 0},
 u'sys': {u'country': u'CA',
          u'message': 0.0467,
          u'sunrise': 1397644810,
          u'sunset': 1397693338},
 u'weather': [{u'description': u'light rain'
               u'icon': u'10d',
               u'id': 500,
               u'main': u'Rain'}],
 u'wind': {u'deg': 168.001, u'speed': 3.52}}

我如何解决列表中的项目? 例如,仅打印临时温度,并可能将其用作变量。 例如:

temp = *not sure what to put here*
print temp

现在您有了结果:

results = r.json()

就像其他Python字典一样访问它:

main = results['main']  # Get the 'main' key's value out of results
temp = main['temp']  # Get the 'temp' key's value out of main
print temp

或更简洁(以及您在现实生活中几乎总是这样写的方式):

print results['main']['temp']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM