如何在字典中添加列表元素

2024-05-14 07:19:51 发布

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

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

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)

任何帮助都将不胜感激!


Tags: ofinnumberfordefcountitemsitem
3条回答

关于“幻想游戏清单的列表到字典功能”的问题-第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)

另一种方式:

使用集合模块:

>>> import collections
>>> a = {"a": 10}
>>> b = ["a", "b", "a", "1"]
>>> c = collections.Counter(b) + collections.Counter(a)
>>> c
Counter({'a': 12, '1': 1, 'b': 1})
>>> sum(c.values())
14

您只需迭代列表,并根据已经存在的键增加计数,否则将其设置为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}

您可以用^{}简洁地编写相同的内容,如下所示

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

^{}函数将返回字典中所有值的视图。在我们的例子中,它是数字,我们只是用sum函数将它们全部相加。

相关问题 更多 >

    热门问题