簡體   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