简体   繁体   中英

How do I access a value from a dictionary within a dictionary that is a string

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

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}

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