Yi Zhou
Yi Zhou

Reputation: 315

Adding a list to a dictionary with the simplest code in python 3.x

The inventory parameter is a dictionary representing the player’s inventory and the addedItems parameter is a list. The addToInventory() function should return a dictionary that represents the updated inventory.The program should output the following:

Inventory:

45 gold coin
1 rope
1 ruby
1 dagger

Total number of items: 48

Here's my code:

def addToInventory(inventory, addedItems):
    print('Inventory:')
    totalItem = 0
    for i in range(len(addedItems)):
        if addedItems[i] in inventory:
        inventory[str(addedItems[i])] += 1
    if addedItems[i] not in inventory:
        inventory[str(addedItems[i])] = 1
    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        totalItem += int(v)

    print('Total number of items:' + str(totalItem))

inv = {'gold coin':42,'rope':1}
dragonLoot = ['gold coin','dagger','gold coin','gold coin','ruby']
inv = addToInventory(inv,dragonLoot)

I was wondering how to work on the for loop bit. It seems strange to me now (and way too long). Thx!

Upvotes: 1

Views: 145

Answers (2)

timgeb
timgeb

Reputation: 78670

You really should use a Counter for this, which is a subclass of the builtin dictionary.

It has three advantages for your use case:

  • It is very easy to add two Counter instances (i.e. two inventories together).
  • It is very easy to update a Counter.
  • The Counter will automatically return 0 when you look up any item that is not in the inventory.

Demo:

>>> from collections import Counter
>>> inventory = Counter({'gold': 45,
...                      'rope': 1,
...                      'ruby': 1,
...                      'dagger': 1}
... )
>>> 
>>> def addToInventory(inventory, addedItems):
...     inventory.update(addedItems)
... 
>>> addToInventory(inventory, ['gold', 'gold', 'gold', 'dagger'])
>>> inventory
Counter({'gold': 48, 'dagger': 2, 'rope': 1, 'ruby': 1})
>>> addToInventory(inventory, {'ruby':100})
>>> inventory
Counter({'ruby': 101, 'gold': 48, 'dagger': 2, 'rope': 1})
>>> inventory['gold']
48
>>> inventory['flux capacitor']
0

Upvotes: 3

zondo
zondo

Reputation: 20336

You can make it look like this:

for i in range(len(addedItems)):
    inventory[i] = inventory.get(i, 0) + 1

Upvotes: 0

Related Questions