[英]How to fix 'AttributeError: 'NoneType' object has no attribute 'get' error in python
[英]Cant fix Python error AttributeError: 'int' object has no attribute 'get'
我的源代码
def display_inventory(inventory):
print("Itme list")
item_total = 0
for k,v in inventory.items():
print(str(k) + str(v))
item_total = item_total + v.get(k,0)
print("The total number of items:" + str(item_total))
stuff = {'rope':1, 'torch':6, 'coin':42, 'Shuriken':1, 'arrow':12}
display_inventory(stuff)
错误信息
AttributeError: 'int' object has no attribute 'get'
你能告诉我如何解决这个错误吗? 如果您也能解释为什么这不起作用,我将不胜感激。
先感谢您
get
应该在字典上调用(即inventory
)。get
因为v = inventory[k]
在循环中。k
不存在,则不需要设置默认值,因为for k,v in inventory.items()
仅循环通过现有项目。您为什么不简单地编写以下内容:
def display_inventory(inventory):
print("Itme list")
item_total = 0
for k,v in inventory.items():
print(str(k) + str(v))
item_total = item_total + v # <<< CHANGE HERE
print("The total number of items:" + str(item_total))
stuff = {'rope':1, 'torch':6, 'coin':42, 'Shuriken':1, 'arrow':12}
display_inventory(stuff)
因为在这种情况下,值v
是与您要加起来的产品相对应的数字。 无需使用get()
进行任何进一步的字典查找,因为您已经拥有所需的值。
在您的字典中, v
是 integer。 字典中的所有内容都在inventory.items()
中获取。而您正试图从整数中获取一些东西。 因此它显示一个错误。 解决方案只是更改为v
def display_inventory(inventory: dict):
print("Item list")
item_total = 0
for k,v in inventory.items():
print(str(k) + str(v))
item_total = item_total + v #=== Here
print("The total number of items:" + str(item_total))
stuff = {'rope':1, 'torch':6, 'coin':42, 'Shuriken':1, 'arrow':12}
display_inventory(stuff)
和 output:
rope1
torch6
coin42
Shuriken1
arrow12
The total number of items:62
该错误与v.get(k,0)
。 .get()
function 的语法是
<dict>.get(<key>, <default value if key not found>
并在字典中输出一个值,
而如果键不存在,通常的<dict>[<key>]
方法会抛出错误。
特定于您的代码在迭代for k,v in inventory.items():
的键值对时,该键保证存在。
而且由于您已经在遍历字典中的值,所以您可以简单地使用
item_total += v
。
关于print(str(k) + str(v))
的其他反馈,您可以尝试以下操作:
+
表示法print(str(k) + ' ' + str(v))
只允许string
string
和list
混合,
符号print(k, v)
print("The total number of items:", item_total)
中使用,
表示法Output
rope 1
torch 6
coin 42
Shuriken 1
arrow 12
The total number of items: 62
顺便说一句print("Itme list")
有错别字。
干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.