为什么我的代码中包含KeyError主代码?

时间:2019-07-18 17:36:03

标签: python

我已经做了很多尝试来解决问题,但是每次遇到同样的问题时……主要城市“天气”中的关键错误

import requests
from django.shortcuts import render
from .models import City
from .forms import CityForm

# Create your views here.

def weather(request):

    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=f5f13c3f6d997b396795738b674115cc'
    city = 'Delhi'


    if request.method == 'POST':
        form = CityForm(request.POST)
        form.save()

    form = CityForm()

    cities = City.objects.all()

    weather_data = []

    for city in cities:

        r = requests.get(url.format(city)).json()
        #print(r.text)
        city_weather = {
            'city': city.name,
            'temperature': r['main']['temp'],
            'description': r['weather'][0]['description'],
            'icon':  r['weather'][0]['icon']

        weather_data.append(city_weather)

    print(weather_data)

    #print(city_weather)
    context = {'weather_data': weather_data, 'form': form}
    return render(request, 'weather.html', context)

我希望没有错误,但是我得到了 '温度':r ['main'] ['temp'], KeyError:“主要”

2 个答案:

答案 0 :(得分:0)

city_weather = {
            'city': city.name,
            'temperature': r['main']['temp'],
            'description': r['weather'][0]['description'],
            'icon':  r['weather'][0]['icon']
               } #you need to close the dictionary here

    weather_data.append(city_weather)

答案 1 :(得分:0)

每当您看到KeyError时,语义含义是找不到正在寻找的密钥。 只需在字典“ city_weather

中加入大括号('}')