Adding items from a list to a dictionary in Python [closed]

匿名 (未验证) 提交于 2019-12-03 02:29:01

问题:

I'm currently doing the second exercise found here. https://automatetheboringstuff.com/chapter5 ("List to Dictionary Function for Fantasy Game Inventory")

The task is to add the items from a list to a dictionary.

For some weird reason, my for loop is not looping through the whole list. Can you help me to understand why?

def addToInventory(inventory, addedItems):     for i in addedItems:         if i in inventory:             inventory[i] = inventory[i] + 1         else:             inventory[i] = 1         return inventory  inv = {'gold coin': 42, 'rope': 1} dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] inv = addToInventory(inv, dragonLoot) print(inv) 

When I run this code, the result is "{'rope': 1, 'gold coin': 43}" So the value of the gold coin key is increased by 1 (not by 3 which it is supposed to), and 'dagger' and 'ruby' are ignored.

I have found a working solution elsewhere, but I really want to understand why this code doesn't work.

Thanks in advance.

回答1:

def addToInventory(inventory, addedItems):     for i in addedItems:         if i in inventory:             inventory[i] = inventory[i] + 1         else:             inventory[i] = 1     return inventory 

(return after for, not after if.)



回答2:

The problem was a simple indentation typo. Now if we were trying to write some more efficient/pythonic code, we could just use collections.Counter which is a specialized dictionary type which counts items. Your code can be shortened and optimized:

from collections import Counter  inv = Counter({'gold coin': 42, 'rope': 1})  inv.update(['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'])  print(inv) 

result:

Counter({'gold coin': 45, 'rope': 1, 'dagger': 1, 'ruby': 1}) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!