1

I have been working on an assignment for a Computer Science 30 course. In this assignment I have been asked to access a API and return a specific value that is not just the whole dictionary. My problem is that I can't seem to print the value I want because it is a string and not a integer or a slice. Here is my full code for you if you decide to offer me assistance. Thank You for your time.

import requests
import urllib.parse

# set up a temporary copy of the google api
temp = "https://maps.googleapis.com/maps/api/directions/json?
origin=Disneyland&destination=Universal+Studios+Hollywood4"

# set up the main API and the origin and destination inputs from the user
main_api = "https://maps.googleapis.com/maps/api/directions/json?"
origin = str(input("Enter in the place that is you are going away from: "))
destination = str(input("Enter the destination that you would like to reach: 
"))

# set up the url from the main api, the origin, and the destination
url = main_api + urllib.parse.urlencode({"origin": origin, "destination": 
destination})
# print the url back to the user
print(url)

# show the user the distance between the origin and the destination
json_data = requests.get(url).json()
print(json_data['routes']['legs']['distance']['text'])
  • hi you looking for something like this?https://stackoverflow.com/questions/10399614/accessing-value-inside-nested-dictionaries – NoobProgrammer Jan 19 '18 at 03:44

1 Answers1

0

You have several lists nested within the json dict response. Check the below result out!

json_data['routes'][0]['legs'][0]['distance']

Outputs

{'text': '1,153 mi', 'value': 1855409}
Sohaib Farooqi
  • 5,457
  • 4
  • 31
  • 43
jrjames83
  • 901
  • 2
  • 9
  • 22
  • Thanks! That worked! This helped me a lot. Could you maybe tell my why this worked though? I would like to learn from this. – Lightning Storm Dragon Jan 19 '18 at 07:59
  • It's a very common pattern when dealing with API's, especially when dealing with lots of data. The way I figure out how to get the correct level or indexing is like: call json_data.keys(), check the keys of the dict, find the key I need, then look at it. You may see that it's a list, with dictionaries within it, then call json_data['mykey'][0].keys(), then inspect what further keys you need to pull out. I'd say almost all API's I've worked with have followed this pattern, at least from Google. – jrjames83 Jan 19 '18 at 15:12