简体   繁体   English

我在 python 3 中遇到关于 Keyerror 的错误

[英]I got an error in python 3 about Keyerror

I got this code from udemy course:我从 udemy 课程中得到了这段代码:

    def choose_magic(self):
     i = 1
     print(bcolors.OKBLUE + bcolors.BOLD + "Magic" + bcolors.ENDC)
     for spell in self.magic:
        print(str(i) + ":", spell["name"], "(cost:", str(spell["cost"]) + ")")
        i += 1

When I try to call this function I got this error:当我尝试调用此 function 时,出现此错误:

print(str(i) + ":", spell["name"], "(cost:", str(spell["cost"]) + ")")
KeyError: 'cost'

I got this from udemy course and when I try to run return that error.我从 udemy course 得到这个,当我尝试运行时返回该错误。

The spell dict doesn't have a "cost" key. spell字典没有"cost"键。 You'll need to look at where it's initialized (ie the members of self.magic ).您需要查看它的初始化位置(即self.magic的成员)。

FWIW, this print statement: FWIW,此print声明:

print(str(i) + ":", spell["name"], "(cost:", str(spell["cost"]) + ")")

works a lot better in Python 3 as an f-string:在 Python 3 作为 f 字符串时效果更好:

print(f"{i}: {spell['name']} (cost: {spell['cost']})")

but you still need to sort out that cost thing before it'll work.但是你仍然需要在它起作用之前解决这个cost问题。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python 没有结果和 KeyError:1 - Python got no result and KeyError:1 有关python keyerror的错误 - A mistake about python keyerror 将 Python 3.9 与 .networkx package 一起使用,出现错误:KeyError - Using Python 3.9 with the networkx package and got the error: KeyError python pandas dataframe 列句encode got error KeyError: 6 - python pandas dataframe column sentence encode got error KeyError: 6 python 得到结果,这里是 keyerror: 1 - python got result and here is keyerror: 1 我收到有关python TypeError的错误:'NoneType'对象没有属性'__getitem__' - i got error about python TypeError: 'NoneType' object has no attribute '__getitem__' 我正在使用 LBPH 算法,但我的面部识别和出勤出现此错误“raise KeyError(key) from err KeyError: 'Id'” function - I am using LBPH algorithm but I got this error “raise KeyError(key) from err KeyError: 'Id' ” for my face recognize and attendance function 我在 python 中遇到错误 10061 - i got error 10061 in python 使用'npm install -g appium@1.8.1'安装appium时出现关于python版本错误的错误消息 - I got an error message about python version error when installing appium using 'npm install -g appium@1.8.1' 我在 Python 中遇到此错误,EnvironmentNotWritable 错误 - I got this error in Python, EnvironmentNotWritable Error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM