【发布时间】:2015-05-13 07:12:41
【问题描述】:
假设我有 dict = {'a': 1, 'b': 2'} 并且我还有一个列表 = ['a', 'b, 'c', 'd', 'e'] .目标是将列表元素添加到字典中,并打印出新的 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)
任何帮助将不胜感激!
【问题讨论】:
-
for items in list(): dict.setdefault(item, [])这根本没有意义。 -
如何让 b 为 2?您在哪里进行实际添加?
-
@TimCastelijns - 这就是问题所在。它没有从列表中添加“a”或“b”,而是保留了 dict 的原始值。
-
@thefourtheye - 最后有一个 .append() ,但它给出了一个关于 int 没有方法 .append 的错误,所以我把它拿出来了。还在学习!
标签: python list python-3.x dictionary