[Python] KeyError when trying to pull specific API Response Data

Discussão em 'Python' iniciado por Stack, Janeiro 19, 2025.

  1. Stack

    Stack Membro Participativo

    I want to pull and print dt, temp, weather, humidity and wind speed given the latitude and longitude.

    I thought that using data = r.json() would allow me to access the API Response like a dictionary and be able to access/print the elements I want using print(r[" "]), however, I am getting "KeyError: 'dt'"

    def get_weather(lat,lon):

    import json
    import requests

    r = requests.post('https://api.openweathermap.org/data/2.5/onecall?lat={}&lon={}&exclude=hourly,daily&appid=92d93ccc6ac5587d35d3ccc4479083a1'.format(lat,lon))

    data = r.json()

    dt = data["dt"]
    temp = data["temp"]
    weather = data["weather"]
    humidity = data["humidity"]
    wind_speed = data["wind_speed"]

    print(r["dt"])
    print(r["temp"])
    print(r["weather"])
    print(r["humidity"])
    print(r["wind_speed"])

    get_weather(33,44)

    Continue reading...

Compartilhe esta Página