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

4
假设我有一个字典 = {'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)

非常感谢您的帮助!


3
针对列表中的每个元素:for items in list(): dict.setdefault(item, []) 这段代码完全没有意义。 - thefourtheye
你如何让b变成2?你在哪里进行实际的加法操作? - Tim
@TimCastelijns - 这就是问题所在。它没有从列表中添加'a'或'b',而是保留了字典中的原始值。 - bgrande
@thefourtheye - 在那个末尾有一个 .append(),但它会出现一个关于 int 没有 .append 方法的错误,所以我把它拿掉了。还在学习中! - bgrande
12个回答

11

你只需要迭代列表,在已经存在的键上增加计数,否则将其设置为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函数会查找key,如果找到它将返回对应的value,否则将返回您在第二个参数中传递的值。如果item已经是字典的一部分,则返回与之相对应的数字并加上1,然后将其存储回同一item。如果没有找到,我们将获得0(第二个参数),并将其加1后存储在item中。


现在,要获取总计数,您可以使用sum函数将字典中所有值相加,像这样:

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

dict.values 函数将返回字典中所有值的视图。在我们的情况下,这些值将是数字,我们只需使用 sum 函数将它们全部相加即可。


2

另一种方式:

使用collections模块:

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

2

这是关于“幻想游戏库存列表转字典函数”的问题 - 《Python自动化办公文档》第5章。

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

2
如果你正在寻找《Python自动化办公之道》中与奇幻游戏库存相关的“列表转字典函数”的解决方案,这里有一个可行的代码:
# inventory.py
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}

#this part of the code displays your current inventory
def displayInventory(inventory): 
    print('Inventory:')
    item_total = 0

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

#this launches the function that displays your inventory
displayInventory(stuff) 

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

# this part is the function that adds the loot to the inventory
def addToInventory (inventory, addedItems): 

    print('Your inventory now has:')

#Does the dict has the item? If yes, add plus one, the default being 0
    for item in addedItems:
        stuff[item] = stuff.get(item, 0) + 1 


# calls the function to add the loot
addToInventory(stuff, dragonLoot) 
# calls the function that shows your new inventory
displayInventory(stuff) 

在寻找这个精确练习的解决方案时,这是谷歌上的第一个结果,因此我在这里发布了书中明确要求的解决方案。我不得不从其他答案中学习并进行一些调整。 - Adrien Le Falher

1
使用collections.Counter,因为它拥有你需要完成任务的一切:
from collections import Counter

the_list = ['a', 'b', 'c', 'd', 'e']

counter = Counter({'a': 1, 'b': 2})
counter.update(the_list)

for c in sorted(counter):
    print c, counter[c]

为了获得总数,您可以简单地将counter的值相加:
sum(counter.values())
# 8

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

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

def addToInventory(inventory,addedItems):
    for v in addedItems:
        if v in inventory.keys():
            inventory[v]+=1
        else:
            inventory[v]=1

addToInventory(stuff,dragonLoot)    

displayInventory(stuff)

请解释您的代码,否则它将毫无帮助。 - Robin Ellerkmann

1
invent = {'rope': 1, 'torch':6, 'gold coin': 42, 'dagger':1, 'arrow':12}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

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

def addToInventory(inventory, addedItems):
    for item in addedItems:
        inventory.setdefault(item, 0)
        inventory[item] = inventory[item] + 1
    return(inventory)



displayInventory(addToInventory(invent, dragonLoot))

1

对于您问题的第一部分,为了将列表项添加到字典中,我使用了以下代码:

inventory = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

def addToInventory(inventory, addedItems):
    for i in addedItems:
        if i in inventory:
            inventory[i] = inventory[i] + 1
        else:
            inventory[i] = 1 #if the item i is not in inventory, this adds it
                             #   and gives the value 1.




我分享这个是因为在这里,我使用了if语句而不是.get函数,就像其他评论中提到的一样。现在我学会了.get函数,它似乎比我的代码更简单和更短。但是,在我遇到这个练习的书籍“自动化无聊的事情”的章节中,我还没有学会(或者说掌握得不够好).get函数。
至于显示库存的函数,我有与其他评论相同的代码:
def displayInventory(inventory):
    print('Inventory:')
    tItems = 0 
    for k, v in inventory.items(): 
        print(str(v) + ' ' + k)
    for v in inventory.values():
        tItems += v
    print()
    print('Total of number of items: ' + str(tItems))

我调用了这两个函数,结果如下:
>>> addToInventory(inventory, dragonLoot)
>>> displayInventory(inventory)

Inventory:
45 gold coin
1 rope
1 dagger
1 ruby

Total of number of items: 48


我希望这能帮到您。

0

对于这个问题的第一部分,这是我想出来的代码。

invt = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
print ("Inventory:")
total = sum(invt.values())
for x, v in invt.items():
  print (str(v) + ' ' + x)
print ("Total number of items: {}".format(total))

我看到大多数人都通过循环来添加到总变量中。然而,使用sum方法,我跳过了一步..

始终欢迎反馈....


0

inventory.py

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

#this part of the code displays your current inventory
def displayInventory(inventory): 
    print('Inventory:')
    item_total = 0

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

#this launches the function that displays your inventory
displayInventory(stuff) 

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

# this part is the function that adds the loot to the inventory
def addToInventory (inventory, addedItems): 

    print('Your inventory now has:')

#Does the dict has the item? If yes, add plus one, the default being 0
    for item in addedItems:
        stuff[item] = stuff.get(item, 0) + 1 


# calls the function to add the loot
addToInventory(stuff, dragonLoot) 
# calls the function that shows your new inventory
displayInventory(stuff) 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接