简体   繁体   中英

Using the data for 'requests' module in python

I am able to load in some weather data from the requests module for python with the following code:

 from pprint import pprint
import requests

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

pprint(r.json())

But how do I actually use the data it produces? I cannot for the life of me find the relevant documentation or tutorial on how to do this. this is the output of the 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}}

How could I address an item within the list? For example to print just the temp on it's own and maybe to use it as a variable. Eg:

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

Now that you have the results:

results = r.json()

just access it like any other Python dict:

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

or more tersely (and the way you'd almost always write this in real life):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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