假设我有 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)
任何帮助将不胜感激!
最佳答案
您只需要迭代列表并增加对键的计数(如果它已经存在),否则将其设置为 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
添加到它并将它存储回相同的 项目
。如果没有找到,我们将得到 0(第二个参数),然后将其加 1 并将其存储在 item
中。
现在,要获得总计数,您只需使用 sum
函数将字典中的所有值相加,如下所示
>>> sum(d.values())
8
dict.values
函数将返回字典中所有值的 View 。在我们的例子中,它将是数字,我们只需使用 sum
函数将它们全部相加。
关于python - 如何将列表元素添加到字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30208044/