[Python-es] [Consulta] KeyError: 'main'

Lemarchand Barker lemarchand8679 en gmail.com
Jue Jul 2 10:44:25 EDT 2020


Hola, estoy teniendo un inconveniente a la hora de correr un programa.

El código es este:

base_url = "http://api.openweathermap.org/data/2.5/weather?q="

city_name = input("Ingrese nombre de la ciudad: ")

complete_url = base_url + "appid=" + api_key + "&q=" + city_name

response = requests.get(complete_url)

x = response.json()

if x["cod"] != "404":
    y = x['main']
    # y = x["cod"]
    current_temperature = y["temp"]
    current_pressure = y["pressure"]
    current_humidiy = y["humidity"]
    z = x["weather"]
    weather_description = z[0]["description"]

    print(
        "Temperature (in centigrade unit) = " +
        str(current_temperature) +
        "\n atmospheric pressure (in hPa unit) = " +
        str(current_pressure) +
        "\n humidity (in percentage) = " +
        str(current_humidiy) +
        "\n description = " +
        str(weather_description)
    )
else:
    print(" Ciudad no encontrada ")

El problema se da cuando intento ingresar una ciudad. Probé con la mía
Corrientes (Argentina) y me da KeyError, probé con otra localidad y es lo
mismo.
La salida es la siguiente:

/usr/bin/python3.8 /home/raiden/Programacion/weather/tiempo.py
Ingrese nombre de la ciudad: London
Traceback (most recent call last):
  File "/home/raiden/Programacion/weather/tiempo.py", line 18, in <module>
    y = x['main']
KeyError: 'main'

Leí que generalmente ese error se debe a que no encuentra el path o no
existe. Probé cambiar en la línea 18 el "main" por "cod" y el error ya es
otro. Es el siguiente:

/usr/bin/python3.8 /home/raiden/Programacion/weather/tiempo.py
Ingrese nombre de la ciudad: London
Traceback (most recent call last):
  File "/home/raiden/Programacion/weather/tiempo.py", line 20, in <module>
    current_temperature = y["temp"]
TypeError: 'int' object is not subscriptable

Asi que por eso comenté la línea como se ve en el código, porque me parece
que mi problema es con main.

El código original es este:
Python-find-current-weather-of-any-city-using-openweathermap-api/
<https://www.geeksforgeeks.org/python-find-current-weather-of-any-city-using-openweathermap-api/>

Saludos
------------ próxima parte ------------
Se ha borrado un adjunto en formato HTML...
URL: <http://mail.python.org/pipermail/python-es/attachments/20200702/0c78e31a/attachment.html>


Más información sobre la lista de distribución Python-es