标签: keyerror

安装django-scheduler:$ python manage.py runserver返回KeyError:你'__ module__'

我用pip安装了django-scheduler(https://github.com/llazzaro/django-scheduler),我在教程中编辑了settings.py.当我运行$ python manage.py runserver时,我得到了这个:

python manage.py runserver
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 354, in execute
    django.setup()
  File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 21, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/usr/local/lib/python2.7/dist-packages/django_scheduler-0.7.5-py2.7.egg/schedule/models/__init__.py", line 1, in <module>
    from schedule.models.calendars import *
  File "/usr/local/lib/python2.7/dist-packages/django_scheduler-0.7.5-py2.7.egg/schedule/models/calendars.py", line 110, in …
Run Code Online (Sandbox Code Playgroud)

django calendar schedule module keyerror

1
推荐指数
1
解决办法
959
查看次数

Django-REST中关系字段的KeyError

我有以下型号:

class ProductColor(models.Model):
    color_title = models.CharField(max_length=50)

class BasicProduct(models.Model):

    product_title = models.CharField(max_length=150)
    product_desc = models.TextField()
    product_price = models.FloatField(default=10.0)

    # Describes what colors are available for this product
    product_colors = models.ManyToManyField(ProductColor)

class BasicCartItem(models.Model):
    cart_product = models.ForeignKey(BasicProduct)
    cart_color = models.ForeignKey(ProductColor, blank=True, default=None, null=True)
Run Code Online (Sandbox Code Playgroud)

和我的ModelSerializer:

class CartSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.BasicCartItem
Run Code Online (Sandbox Code Playgroud)

我正在给出我的观点:

{'cart_product': 1}
Run Code Online (Sandbox Code Playgroud)

然后运行代码:

    m = CartSerializer(data=inputdata)
    if m.is_valid():
        items = m.data # Generates KeyError: u'cart_color'
Run Code Online (Sandbox Code Playgroud)

stacktrace的摘录:

  File "python2.7/site-packages/rest_framework/serializers.py", line 430, in to_representation
    attribute = field.get_attribute(instance)
  File "python2.7/site-packages/rest_framework/relations.py", line 103, in get_attribute …
Run Code Online (Sandbox Code Playgroud)

django many-to-many foreign-keys django-rest-framework keyerror

1
推荐指数
1
解决办法
1219
查看次数

如何处理空字典值

我有一个字典形式的json列表,以下允许我从字典中获取值:

valone = out['red']['blue']['green']

valtwo = out['purple']['yellow']['black']
Run Code Online (Sandbox Code Playgroud)

从那里我可以围绕valone或valtwo运行条件语句,看看它们是否是绿色的黑色.

现在这种方法很有效,当这些键被填充时,但是当它们不是我得到的时候

KeyError: 'black'
Run Code Online (Sandbox Code Playgroud)

这是我可以看到的值是空的.

我很难在声明dict值之前弄清楚如何过滤掉.

我见过人们的建议

out.get("black", None)
Run Code Online (Sandbox Code Playgroud)

但我不能访问黑色,因为我是它的第三个价值?

python dictionary keyerror

1
推荐指数
1
解决办法
94
查看次数

Python:使用get()后的键错误

我这里有一个代码,用于计算以"From"开头的行中类似的第二个单词的数量,找出哪个出现最大次数并打印该单词及其频率.

在使用get方法的行上,我得到一个Key Error :(在这里插入第二个单词).第一个句子本身会发生此键错误,并且循环不会迭代.我完全不知道为什么会这样.

name = raw_input("Enter file:")
fh = open(name)
d=dict()
max=0
key=''
for line in fh:
    line=line.rstrip()
    if line.startswith('From '):
        x=line.split()
        d[x[1]] = d.get(d[x[1]],0) + 1
for z in d:
    if d[z]>max:
        max=d[z]
        key = z
print key, max
Run Code Online (Sandbox Code Playgroud)

谢谢.

python keyerror

1
推荐指数
1
解决办法
432
查看次数

Python/Pandas - KeyError合并数据帧

我有两个数据帧我正在尝试合并:

target:

    version  city_id            code
id                                                                            
4         2        4   5736201000175   
26        2        3   8290265000183   
27        3        3   9529184000156   
30        3        3   9263064000150   
34        2        3   9312770000144   
54        1        3   8407830000140   
55        1        3   5590100000139   



city:

    federation_unit_id       name
id                                        
3                    8  SAO PAULO
4                    8   CAMPINAS
7                    8    BARUERI
8                    8  BEBEDOURO
9                    8     SANTOS
Run Code Online (Sandbox Code Playgroud)

我想合并它们将target's"city_id"与city's"id" 合并在一起,最终数据框如下所示:

target:

    version  city_id            code    federation_unit_id       name
id                                                                            
4         2        4   5736201000175                     8   CAMPINAS
26        2        3   8290265000183                     8  SAO PAULO …
Run Code Online (Sandbox Code Playgroud)

python merge pandas keyerror

1
推荐指数
1
解决办法
4376
查看次数

用不同的方法使用美丽的汤来获取href

我正在尝试抓取一个网站。我学会了从两种资源中抓取:一种用于tag.get('href')a标签中获取 href ,另一种用于tag['href']获取相同的内容。据我了解,他们都做同样的事情。但是当我尝试这段代码时:

link_list = [l.get('href') for l in soup.find_all('a')]
Run Code Online (Sandbox Code Playgroud)

它适用于该.get方法,但不适用于字典访问方式。

link_list = [l['href'] for l in soup.find_all('a')]
Run Code Online (Sandbox Code Playgroud)

这会抛出一个KeyError. 我对刮刮很陌生,所以如果这是一个愚蠢的,请原谅。

编辑 - 这两种方法都适用于 find 方法而不是 find_all。

python beautifulsoup keyerror

1
推荐指数
1
解决办法
8474
查看次数

枚举数据加载器时出现 KeyError

我正在尝试遍历初始化如下的 pytorch 数据加载器:

trainDL = torch.utils.data.DataLoader(X_train,batch_size=BATCH_SIZE,shuffle=True,**kwargs)

其中 X_train 是一个像这样的熊猫数据框: 我的熊猫 DF

因此,我无法执行以下语句,因为我在“枚举”中收到 KeyError:

for batch_idx, (data, _) in enumerate(trainDL):
    {stuff}
Run Code Online (Sandbox Code Playgroud)

有没有人知道发生了什么?

编辑:

我得到的错误是:

KeyError                                  Traceback (most recent call last)
~/.local/share/virtualenvs/Pipenv-l_wD1rT4/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2896             try:
-> 2897                 return self._engine.get_loc(key)
   2898             except KeyError:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 40592

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-63-95142e0748bb> in <module>
----> 1 for batch_idx, (data, _) …
Run Code Online (Sandbox Code Playgroud)

python keyerror pytorch dataloader

1
推荐指数
1
解决办法
4275
查看次数

字典列表在 Python 中引发了一个关键错误

我有一个字典列表,我想分别计算“增加”和“减少”键的值。我的脚本返回了一个关键错误,这可能是因为并非所有词典都有“增加”和“减少”。但我不知道如何解决它。作为 Python 初学者,任何帮助将不胜感激。

list_of_dicts = [{"decreasing": 1}, {"increasing": 4}, {"decreasing": 1}, {"increasing": 3},{"decreasing": 1},
             {"increasing": 1}]

values1 = [a_dict["decreasing"] for a_dict in list_of_dicts]
values2 = [a_dict["increasing"] for a_dict in list_of_dicts]

print(values1)
print(values2)
Run Code Online (Sandbox Code Playgroud)

预期的结果是:

[1,1,1]
[4,3,1]
Run Code Online (Sandbox Code Playgroud)

python dictionary list keyerror

1
推荐指数
1
解决办法
43
查看次数

KeyError 迭代列表中的键

大家好,所以我写了一个类似这样的函数

def solve_one_shop(shop, items):
    if len(items) == 0:
        return [0.0, []]
    all_possible = []
    first_item = items[0]
    print shop['burger']
    for (price,combo) in shop[first_item]:
        # DO SOMETHING
        #

solver(shop_text,['burger'])
Run Code Online (Sandbox Code Playgroud)

我试图迭代的字典是这样的:

{'1': {'burger': [[4.0, ['burger']]], 'tofu_log': [[8.0, ['tofu_log']]]}, '3': {'chef_salad': [[4.0, ['chef_salad']]], 'steak_salad_sandwich': [[8.0, ['steak_salad_sandwich']]]}, '2': {'burger': [[5.0, ['burger']]], 'tofu_log': [[6.5, ['tofu_log']]]}, '5': {'extreme_fajita': [[4.0, ['extreme_fajita']]], 'fancy_european_water': [[8.0, ['fancy_european_water']]]}, '4': {'wine_spritzer': [[2.5, ['wine_spritzer']]], 'steak_salad_sandwich': [[5.0, ['steak_salad_sandwich']]]}, '6': {'extra_salsa': [[6.0, ['extreme_fajita', 'jalapeno_poppers', 'extra_salsa']]], 'jalapeno_poppers': [[6.0, ['extreme_fajita', 'jalapeno_poppers', 'extra_salsa']]], 'extreme_fajita': [[6.0, ['extreme_fajita', 'jalapeno_poppers', 'extra_salsa']]], …
Run Code Online (Sandbox Code Playgroud)

python dictionary keyerror

0
推荐指数
1
解决办法
8254
查看次数

Python KeyError如果逻辑或尝试逻辑

我正在尝试循环一些JSON数据以导出到CSV并且一切顺利,直到我得到一些我需要获得某些字段值的数据,其中这些字段并不总是存在于"tags"下面.

我收到的错误是:

for alarm in tag["alarmst"]:
        KeyError: 'alarmst'
Run Code Online (Sandbox Code Playgroud)

我相信内置异常读取这意味着键/字段不存在.

我在错误和异常中读到,我可以将此逻辑放在try语句中,如果此键不存在,请不要给我错误并执行其他操作或转到"tag"下面的下一组记录中"alarmst"就是将该(以及指定的其他字段)转储到该文件中.

我无法弄清楚如何告诉这个逻辑停止给我这个错误,并且只使用csv_file.writerow()带有所有字段值的函数(如果只存在"alarmst").

由于我将在这个Python进程运行之前使用一个文件和进程将"devs"和"tags"添加到他们自己的CSV文件中,我无法解析数据并减少for循环中的for循环.

我不确定这个问题if tag["alarmst"] in tag:是否是由于其他人中存在如此多的for循环,或者我是否需要以某种方式使用try语句,或者如果我因为我是新的而没有正确地做其他事情在这个级别的编码Python,但它似乎适用于迄今为止的需要.

我在Windows 10操作系统上运行它,如果这有任何区别,但我认为它没有.

启动代码:

import json
import csv

with open('C:\\folder\\dev\\TagAlarms.txt',"r") as file:
    data = json.load(file)

with open('C:\\folder\\dev\\TagAlarms.csv',"w",newline='') as file:
    csv_file = csv.writer(file)
    for dev in data["devs"]:
        for tag in dev["tags"]:
            for alarm in tag["alarmst"]:
                csv_file.writerow(alarm['dateStatus'],[alarm['dateStart'], alarm['status'], alarm['type']])
Run Code Online (Sandbox Code Playgroud)

如果代码:

import json
import csv

with open('C:\\folder\\dev\\TagAlarms.txt',"r") as file:
    data = json.load(file)

with open('C:\\folder\\dev\\TagAlarms.csv',"w",newline='') as file:
    csv_file = …
Run Code Online (Sandbox Code Playgroud)

python dictionary python-3.x keyerror

0
推荐指数
1
解决办法
230
查看次数