这个美好社区中忙碌的程序员。
我正在尝试完成一本名为“自动化无聊的东西”的书中的任务。在这里,我尝试将此 DragonLoot[] 列表附加到 itemsSatchel{} 字典中。在将列表更改为字典后,我尝试使用此更新属性,但失败了,所以我真的不知道该怎么办。帮助!
import pprint
itemsSatchel = {'Arrow': 12,
'Gold Coin': 42,
'Rope': 1,
'Torch': 6,
'Dagger':1}
dragonLoot = ['Gold Coin',
'Gold Coin'
'Dagger'
'Gold Coin',
'Ruby']
def addToSatchel(self):
#This part is my pain in the ___#
def displaySatchel(self):
print("Inventory: ")
itemsCounter = 0
for k,v in itemsSatchel.items() :
pprint.pprint(str(v) + ' ' + str(k))
itemsCounter += v
print('Total number of items: ' + str(itemsCounter))
addToSatchel({dragonLoot})
displaySatchel(itemsSatchel)
最佳答案
您还可以考虑使用collections.Counter
这里。它可以从dict
或项目列表更新。
from collections import Counter
itemsSatchel = Counter({'Arrow': 12,
'Gold Coin': 42,
'Rope': 1,
'Torch': 6,
'Dagger':1})
dragonLoot = ['Gold Coin', ...]
def addToSatchel(items):
itemsSatchel.update(items)
addToSatchel(dragonLoot)
关于python - 如何编写一个将列表添加到字典的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55293848/