ditamoxcit
ditamoxcit

Reputation: 3

Extract multiple data into same dictionary using API Python JSON

I am able to extract the specific data from the url.

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

The question is, how can i extract multiple data and put in a 1 list (dict) rather than extract it one by one.

Here what is displayed from 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}}

Output expected may like this:

{'name' :London, 'country': GB, 'humidity' :88, 'lat' :51.51}

Upvotes: 0

Views: 86

Answers (2)

oxdeadbeef
oxdeadbeef

Reputation: 180

Since your key mappings are not exact the simplest seems best.

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}

Upvotes: 0

Cody Bouche
Cody Bouche

Reputation: 955

You will have to use dictionary comprehension per index then merge everything back to the original dictionary. Something like this...

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

Upvotes: 1

Related Questions