user3599920
user3599920

Reputation: 13

Simple python TypeError: list incides

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



def addToInventory(inventory,loot):
    for i in loot:
        if loot[i] in inventory.keys:
            inventory.update((loot[i]), +1)
        else:
            inventory.setdefault(loot[i], 1)
    print(inventory)


addToInventory(stuff,dragonLoot) 

I'm trying to check if an item exists in my stuff list from loot. I get:

TypeError: list indices must be integers or slices, not str. 

Upvotes: 0

Views: 34

Answers (2)

John Bartels
John Bartels

Reputation: 2763

In reference to the TypeError that you are seeing, dragonLoot is a list and when you iterate over a list, the objects in the list are returned. For example, "gold coin" would be returned as one of these objects. You are then attempting to access the item in the list by using the string value as its index value: dragonLoot["gold coin"]. This will not work as you can only access items in a list by their index location: dragonLoot[0]. You can access an item in a dictionary by its key such as: inventory["gold coin"] which will return the value associated with that key.

I was having trouble with the update method. I would use the key to set the value for the object in the inventory:

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

def addLootToInventory(lootArray):
    for lootObjectKey in lootArray:
        if lootObjectKey in inventory.keys():
            # set the objects new value equal to its current value plus one
            inventory[lootObjectKey] = inventory[lootObjectKey] + 1
        else:
            # the key does not yet exist in the inventory dictionary, create and set to one
            inventory[lootObjectKey] = 1
    print(inventory)

addLootToInventory(dragonLoot)

After which, the output was:

{'gold coin': 45, 'dagger': 2, 'torch': 6, 'rope': 1, 'arrow': 12, 'ruby': 1}

Upvotes: 0

TerryA
TerryA

Reputation: 59974

I think you're introducing a variable you don't want to. You're trying to update your inventory, but your inventory is the dragonLoot?

My suggestion would be to have another variable called inventory = {} (EDIT: I didn't realise stuff was your main inventory, so that is your main variable), and get rid of your second parameter in your function. You don't need it. You'd do it like so:

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


def addToInventory(loot):
    for i in loot:
        if i in stuff:
            stuff[i] += 1
        else:
            stuff[i] = 1
    print(stuff)


addToInventory(dragonLoot) 

I've also cleaned up your code :)

Upvotes: 1

Related Questions