Python 如何使用dict.update()更新词典?

Python 如何使用dict.update()更新词典?,python,python-3.x,list,dictionary,Python,Python 3.x,List,Dictionary,我试图使用dict.update()向字典(stuff)添加和更新键和值,但它没有更新字典。下面的代码只显示初始字典两次 stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} def displayInventory(inventory): print('Inventory:') for k, v in inventory.items(): print(str(v)+

我试图使用dict.update()向字典(stuff)添加和更新键和值,但它没有更新字典。下面的代码只显示初始字典两次

stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}

def displayInventory(inventory):
    print('Inventory:')
    for k, v in inventory.items():
        print(str(v)+' '+k)
        
displayInventory(stuff)
print('Total number of items: ' + str(sum(stuff.values())))

dragonLoot={'gold coin': 42, 'rope': 1}
dragonLoot.update(stuff)
print("Dragon's loot added: 42 gold coins and 1 rope")
displayInventory(dragonLoot)
print('Total number of items: ' + str(sum(dragonLoot.values())))
.update()
不是那样工作的。我已经做了一个可以工作的函数。如果您有任何问题,请留下评论

stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}

def displayInventory(inventory):
    print('Inventory:')
    for k, v in inventory.items():
        print(str(v)+' '+k)

def updateInventory(inventory,loot):
    for item in loot:
        if item in inventory:
            inventory[item] += loot[item]
        else:
            inventory[item] = loot[item]
    return inventory
    
displayInventory(stuff)
print('Total number of items: ' + str(sum(stuff.values())))

dragonLoot={'gold coin': 42, 'rope': 1}
stuff = updateInventory(stuff,dragonLoot)
print("Dragon's loot added: 42 gold coins and 1 rope")
displayInventory(stuff)
print('Total number of items: ' + str(sum(stuff.values())))

这确实有效,但您无法判断,因为您正在将密钥更新为相同的值。您是否希望添加这些值?