将两个拥有相同键的字典相加

2024-06-16 12:52:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数,用于添加以下项的两个字典(“item_name”:item数量)。有一个错误,我修复了它,但我不明白它是如何工作的。在

这是我的原始代码,它不能正常工作。在

inventory = {'rope': 1, 'torch': 5, 'gold': 3000, 'dagger': 1}
loot = {'lock pick': 3, 'potion' : 1, 'lock pick': 4, 'potion' : 1, 'sword': 1}

def addToInventory(inventory, addedItems):
  for item, quantity in addedItems.items():
    inventory.setdefault(item, 0)
    inventory[item] += quantity

addToInventory(inventory, loot)

当战利品中有相同的物品时,它不会将它们的数量添加到库存中。在

以下是有效的代码:

^{pr2}$

为什么不能“反转.setdefault(item,quantity)“双重计数必须为其设置默认值的第一个项目吗?在


Tags: 函数代码namelock数量字典itemquantity
3条回答

这条线:

loot = {'lock pick': 3, 'potion' : 1, 'lock pick': 4, 'potion' : 1, 'sword': 1}

未按预期执行,lock pick的第二个实例正在覆盖第一个实例。由于loot是一个字典,因此每个键只能有一个实例。如果要允许一种类型的多个实例,请考虑元组列表:

^{pr2}$

然后你的功能看起来几乎一样:

def addToInventory(inventory, addedItems):
    for item, quantity in addedItems:
        inventory.setdefault(item, 0)
        inventory[item] += quantity       

您的loot字典有重复的键。所以只有其中一个会被添加到字典中。你应该使用元组列表或者类似的东西。在

inventory = {'rope': 1, 'torch': 5, 'gold': 3000, 'dagger': 1}
loot = [('lock pick', 3), ('potion', 1), ('lock pick', 4), ('potion', 1),
        ('sword', 1)]


def addToInventory(inventory, addedItems):
    for item, quantity in addedItems:
        # This will get the existing value and add quantity to it. If the key
        # does not exist, `inventory.get` will use zero
        inventory[item] = inventory.get(item, 0) + quantity


addToInventory(inventory, loot)
print(inventory)

输出

^{pr2}$

字典中的每个键只能分配一个值。Python的行为似乎是使用为每个键指定的后一个值。在

>>> loot = {'lock pick': 3, 'potion' : 1, 'lock pick': 4, 'potion' : 1, 'sword': 1}
>>> print(loot)
{'lock pick': 4, 'potion': 1, 'sword': 1}
>>>

相关问题 更多 >