2014-04-16 20 views
0

我能夠從請求模塊的一些氣象數據加載蟒蛇用下面的代碼模塊:使用的數據的請求「在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 
+0

我希望壽se溫度在開爾文... –

+0

@DanielRoseman我不知道。這些天在邁阿密非常熱。 –

回答

4

現在你有了結果:

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'] 
+0

我缺少的步驟是通過results = r.json()轉換它。你的回答很好解釋,簡明扼要 - 謝謝你:) –