如何将列表值和数量添加到字典中

时间:2016-01-27 02:48:00

标签: python list dictionary

我正在尝试编写一个for循环,它将获取一个列表并将其值添加到字典中。例如,假设列表包含值:[Book,Coin,Book,Book,Computer,Bag]。 for循环将获取这些值并将其添加到字典中,其键是添加的项的名称,相应的值是项的数量。这是我到目前为止的代码:

import pprint

def addToInventory(inventory, addedItems):
    for i in addedItems:
        inventory += addedItems.count(i)

def displayInventory(inventory):
    print("Inventory:")
    item_total = 0
    for k, v in inventory.items():
        pprint.pprint(str(v) + ' ' + k)
        item_total += v
    print("Total number of items: " + str(item_total))

stuff = {}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

# while True:
#     item = raw_input('Please enter item name')
#     if item == '':
#         break
#     quantity = input('and the number of this item?')
#     stuff.setdefault(item, quantity)
#     print stuff

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

addToInventory(stuff, dragonLoot)
displayInventory(stuff)

3 个答案:

答案 0 :(得分:0)

我认为这就是你要找的东西。关键是只迭代新列表中的唯一项目并添加到现有字典中,或者如果项目不存在则更新项目。

alist = ["Book", "Coin", "Book", "Book", "Computer", "Bag"]
inventory = {"Book":3, "Bag":2}
for item in list(set(alist)): #get the unique items by converting them to a set
    if item in result:
        inventory[item] += alist.count(item) 
    else:
        inventory[item] = alist.count(item)

#inventory would now become {"Book":6, "Coin":1", "Bag":3", "Computer":1}

另外,使用Stefan的方法。 如果库存是柜台,你可以这样做

inventory.update(alist)

答案 1 :(得分:0)

您可以使用collection.Counter

>>> alist = ["Book", "Coin", "Book", "Book", "Computer", "Bag"]
>>> inventory = {"Book":3, "Bag":2}
>>> dict(collections.Counter(inventory) + collections.Counter(alist))
{'Bag': 3, 'Book': 6, 'Coin': 1, 'Computer': 1}

答案 2 :(得分:0)

使用collections.Counter

from collections import Counter

def add_to_inventory(inventory, items):
    inventory.update(items)

def display_inventory(inventory):
    print("Inventory:")
    print('\n'.join('{} {}'.format(v, k) for k, v in inventory.items()))
    print("Total number of items: {}".format(sum(inventory.values())))

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

dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

display_inventory(stuff)
add_to_inventory(stuff, dragon_loot)
display_inventory(stuff)

<强>输出

  

清单:

     

1根绳子

     42金币

     

6火炬

     

1 dagger

     

12箭头

     

项目总数:62

     

清单:

     

45金币

     

2匕首

     

6火炬

     

1根绳子

     

12箭头

     

1 ruby​​

     

项目总数:67