首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么我的代码中有KeyError main?

为什么我的代码中有KeyError main?
EN

Stack Overflow用户
提问于 2019-07-19 01:36:03
回答 3查看 504关注 0票数 2

我已经尝试了很多方法来解决这个问题,但每次我都遇到同样的问题。main上的city_weather中的键错误

代码语言:javascript
运行
复制
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‘,KeyError:’main‘

EN

回答 3

Stack Overflow用户

发布于 2022-01-29 10:35:18

您需要转到管理页面并删除您之前创建的城市,因为您定义了未定义的城市名称,因此会收到一个错误。

票数 1
EN

Stack Overflow用户

发布于 2019-07-19 17:33:56

代码语言:javascript
运行
复制
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)
票数 0
EN

Stack Overflow用户

发布于 2019-07-19 17:47:23

每当您看到KeyError时,其语义含义就是找不到正在查找的键。只需包含字典"city_weather“的右花括号(‘}’

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57099942

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档