繁体   English   中英

Python:将列表添加到字典

[英]Python: Add a list to a dictionary

我想将项目列表添加到现有字典中,但我没有得到正确数量的项目。 这是我的代码。

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)

预期的 output 应该是这个

Inventory:
1 rope
6 torch
5 gold coin
2 dagger
12 arrow
1 ruby
Total number of items: 27

这是因为dict.fromkeys(add, 1)做了一些你认为的其他事情:

dragonLoot = ['gold coin', 'dagger', 'gold coin', 'ruby']
>>> dict.fromkeys(dragonLoot, 1)
{'gold coin': 1, 'ruby': 1, 'dagger': 1}

所以它不计算出现次数。

我会将addToInventory function 更改为:

def addToInventory(inventory, add):
    for k in add:
        inventory[k] = inventory.get(k, 0) + 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

(普通的 dict 会引发KeyError )。

您可能想要使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM