如何将列表元素添加到字典中

新手上路,请多包涵

假设我有 dict = {‘a’: 1, ‘b’: 2’} 并且我还有一个列表 = [‘a’, ‘b, ‘c’, ’d’, ‘e’]。目标是将列表元素添加到字典中并打印出新的字典值以及这些值的总和。应该看起来像:

 2 a
3 b
1 c
1 d
1 e
Total number of items: 8

相反,我得到:

 1 a
2 b
1 c
1 d
1 e
Total number of items: 6

到目前为止我所拥有的:

 def addToInventory(inventory, addedItems)
    for items in list():
        dict.setdefault(item, [])

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

newInventory=addToInventory(dict, list)
displayInventory(dict)

任何帮助将不胜感激!

原文由 bgrande 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 954
2 个回答

您只需要迭代列表并增加对键的计数(如果它已经存在),否则将其设置为 1。

 >>> d = {'a': 1, 'b': 2}
>>> l = ['a', 'b', 'c', 'd', 'e']
>>> for item in l:
...     if item in d:
...         d[item] += 1
...     else:
...         d[item] = 1
>>> d
{'a': 2, 'c': 1, 'b': 3, 'e': 1, 'd': 1}


您可以使用 dict.get 简洁地编写相同的内容,如下所示

>>> d = {'a': 1, 'b': 2}
>>> l = ['a', 'b', 'c', 'd', 'e']
>>> for item in l:
...     d[item] = d.get(item, 0) + 1
>>> d
{'a': 2, 'c': 1, 'b': 3, 'e': 1, 'd': 1}

dict.get 函数会寻找键,如果找到它会返回值,否则会返回你在第二个参数中传递的值。如果 item 已经是字典的一部分,那么将返回与它相对应的数字,我们将 1 添加到它,并将其存储回相同的 item 。如果没有找到,我们将得到 0(第二个参数),然后将其加 1 并将其存储在 item 中。


现在,要获得总数,您可以使用 sum 函数将字典中的所有值相加,如下所示

>>> sum(d.values())
8

dict.values 函数将返回字典中所有值的视图。在我们的例子中,它将编号,我们只需使用 sum 函数将它们全部相加。

原文由 thefourtheye 发布,翻译遵循 CC BY-SA 3.0 许可协议

关于“幻想游戏清单的字典功能列表”的问题 - 第 5 章。用 Python 自动化无聊的东西。

 # This is an illustration of the dictionaries

# This statement is just an example inventory in the form of a dictionary
inv = {'gold coin': 42, 'rope': 1}
# This statement is an example of a loot in the form of a list
dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

# This function will add each item of the list into the dictionary
def add_to_inventory(inventory, dragon_loot):

    for loot in dragon_loot:
        inventory.setdefault(loot, 0) # If the item in the list is not in the dictionary, then add it as a key to the dictionary - with a value of 0
        inventory[loot] = inventory[loot] + 1 # Increment the value of the key by 1

    return inventory

# This function will display the dictionary in the prescribed format
def display_inventory(inventory):

    print('Inventory:')
    total_items = 0

    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        total_items = total_items + 1

    print('Total number of items: ' + str(total_items))

# This function call is to add the items in the loot to the inventory
inv = add_to_inventory(inv, dragon_loot)

# This function call will display the modified dictionary in the prescribed format
display_inventory(inv)

原文由 Ashutosh Kar 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题