簡體   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