我想将项目列表添加到现有字典中,但是我没有获得正确数量的项目。这是我的代码。
d = {'rope': 1, 'torch': 6, 'gold coin': 3, 'dagger': 1, 'arrow': 12}
def displayInventory(inventory):
print('Inventory:')
totnum = 0
for k,v in d.items():
print(v, k)
totnum += v
print('Total number of items: ' + str(totnum))
displayInventory(d)
print()
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'ruby']
def addToInventory(inventory, add):
new= dict.fromkeys(add, 1)
for k, v in new.items():
inventory[k] = v
z = addToInventory(d, dragonLoot)
displayInventory(d)
预期输出应为
Inventory:
1 rope
6 torch
5 gold coin
2 dagger
12 arrow
1 ruby
Total number of items: 27
答案 0 :(得分:1)
这是因为dict.fromkeys(add, 1)
还有其他您认为的事情:
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'ruby']
>>> dict.fromkeys(dragonLoot, 1)
{'gold coin': 1, 'ruby': 1, 'dagger': 1}
因此它不计算发生次数。
我将addToInventory
函数更改为此:
def addToInventory(inventory, add):
for k in add:
inventory[k] = inventory.get(k, 0) + 1
因此,您可以遍历找到的项目并将其添加到库存中
答案 1 :(得分:1)
考虑重组和使用Counter
,如下所示:
from collections import Counter
inventory = Counter({'rope': 1, 'torch': 6, 'gold coin': 3, 'dagger': 1, 'arrow': 12})
def displayInventory():
print('Inventory:')
for k, v in inventory.items():
print(v, k)
print(f'Total number of items: {sum(inventory.values())}')
displayInventory()
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'ruby']
print('--Picked up loot!')
inventory.update(dragonLoot)
displayInventory()
礼物:
Inventory:
1 rope
6 torch
3 gold coin
1 dagger
12 arrow
Total number of items: 23
--Picked up loot!
Inventory:
1 rope
6 torch
5 gold coin
2 dagger
12 arrow
1 ruby
Total number of items: 27
这还意味着,如果您可以安全地检查库存中是否还没有存货,例如:
print(inventory['diamond'])
给出:
0
(正常字典会引发KeyError
)。
答案 2 :(得分:0)
您可能要使用collections.Counter
。如果使用它,则可能如下所示:
d = Counter({'rope': 1, 'torch': 6, 'gold coin': 3, 'dagger': 1, 'arrow': 12})
loot = ['gold coin', 'dagger', 'gold coin', 'ruby']
d.update(loot)
print(d)
# Counter('rope': 1, 'torch': 6, 'gold coin': 5, 'dagger': 2, 'arrow': 12, 'ruby':1)