将整数添加到字典(类型错误:'int'对象不可下标)



我正在尝试在字典中的选定值旁边添加用户输入的数字。我需要这样做,所以很多用户可以添加到同一个字典中,增加计数,但我收到此错误消息


inventory={'p': 0, 'd': 0, 'r': 0}
let = str(input("""From this selection:
1. p
2. d
3. r
Which letter would you like to produce?: """))
bottle_num = int(input("How Many numbers Would You Like?"))
for let in inventory:
inventory[let] + bottle_num
print(inventory[let][0])

产生输出

From this selection:
1. p
2. d
3. r
Which letter would you like to produce?: r
How Many numbers Would You Like?5
Traceback (most recent call last):
File "C:/Users/$$$$$$$$$$/add_to_dict.py", line 12, in <module>
print(inventory[let][0])
TypeError: 'int' object is not subscriptable

$ 符号已添加到

不能索引整数

inventory={'p': 0, 'd': 0, 'r': 0}
let = 'p' # for example 
inventory[let] # == 0
# we cannot index 0[0]

如果您尝试执行:

5[0] # you will get TypeError
# >>> TypeError: 'int' object is not subscriptable

我想你想做什么:

inventory={'p': 0, 'd': 0, 'r': 0}
let = input("""From this selection:
1. p
2. d
3. r
Which letter would you like to produce?: """)

bottle_num = int(input("How Many numbers Would You Like? "))

inventory.update({let:inventory[let] + bottle_num})
print(inventory[let]) 

因此,我们询问要更新字典中的哪个键。键是你的元素,然后我们更新{key: dictionary[key] + value}dictionary[key]给我们当前值,我们将其添加到其中bottle_num

您的问题是您访问字典的方式。请注意以下事项:

inventory = {"p": 0, "d": 0, "r": 0}
let = "p"
print(inventory[let]) # ouputs => 0

这导致您执行以下操作:

print(0[0])

这是给你抛出错误。另一件需要注意的事情是

for let in inventory:
inventory[let] + bottle_num

循环你去。请注意以下循环:

inventory = {"p": 0, "d": 0, "r": 0}
let = "p"
for let in inventory:
print(let)

输出:

p
d
r

也就是说,您正在打印字典的(记住:dict = {key: value}(。您可能正在寻找的是:

inventory = {"p": 0, "d": 0, "r": 0}
let = str(
input(
"""From this selection:
1. p
2. d
3. r
Which letter would you like to produce?: """
)
)
bottle_num = int(input("How Many numbers Would You Like?"))
inventory[let] += bottle_num
print(inventory)

输出:

From this selection:
1. p
2. d
3. r
Which letter would you like to produce?: p
How Many numbers Would You Like? 5
{'p': 5, 'd': 0, 'r': 0}

最新更新