Python List Loop Error: TypeError: list indices must be integers, not str -


what trying check if values in 'dragonloot' exists in dictionairy 'inv' keys. if want add 1 value, if not want create new key value , add 1.

i think have gotten if, else part correct how struggeling loop , reciving typeerror: list indices must integers, not str error. here code:

#inventory , loot value inv = {'gold coin': 42, 'rope': 1} dragonloot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']  #function loop through items in list def displayinventory(inventory):     print('inventory:')     item_total = 0     j, k in inventory.items():         print(str(k) + ' ' + j)         item_total += k     print('total number of items: %s' % str(item_total))  #where problem occur def addtoinventory(inventory, addeditems):     in addeditems:         if addeditems[i] in inventory.keys():             #edit: see error here now, fix after loop working             inventory[addeditems[i]] + 1         else:             inventory.setdefault(addeditems[i], 1)  inv = addtoinventory(inv, dragonloot) displayinventory(inv) 

i have tryed alot of other solutions have found here on stackoverflow nothing trick. maybe other error have caused have nothing loop itself?

full traceback:

traceback (most recent call last): file "c:/users/*****/dropbox/*****", line 19, in   <module> inv = addtoinventory(inv, dragonloot) file "c:/users/*****/dropbox/*****", line 14, in  addtoinventory if addeditems[i] in inventory.keys(): typeerror: list indices must integers, not str 

why not using counter?

#inventory , loot value inv = {'gold coin': 42, 'rope': 1} dragonloot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']  import collections inv = collections.counter(inv) inv.update(dragonloot)  print inv 

produces

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

see pymotw more info on counters


Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -