Before you "shorten" your code make sure it's correct. Currently inv.update
will just overwrite entries!
I would suggest using a Counter
instead of a dict
because it already implements the logic you want:
>>> from collections import Counter
>>> inv = Counter({'arrow': 12, 'gold coin': 42, 'rope': 2, 'torch': 4, 'dagger': 1})
>>> dragon = Counter({'gold coin': 50, 'ruby': 15})
>>> inv.update(dragon)
>>> inv
Counter({'arrow': 12,
'dagger': 1,
'gold coin': 92, # the 42 and 50 are added!
'rope': 2,
'ruby': 15,
'torch': 4})
The only function you used was show_inv
. However the only purpose of this function was to print
a representation of the object, there's not much you can "shorten" there. And it seems correct.
But if you have a "object" (the dict
) and a function for that object, you should consider using a "class" to wrap it. There are methods that allow you to customize the "string"-representation: __str__
and __repr__
so these can be used instead of an explicit function (or method) call:
from collections import Counter
class Inventory(Counter): # subclass Counter
def __str__(self): # overwrite the str-representation (this method is used by "print")
content = ['{} {}'.format(name, cnt) for name, cnt in self.items()]
content.insert(0, 'inventory:')
content.append('total number of items: {}'.format(sum(self.values())))
return '\n'.join(content)
inv = Inventory({'arrow': 12, 'gold coin': 42, 'rope': 2, 'torch': 4, 'dagger': 1})
print(inv)
# inventory:
# arrow 12
# gold coin 42
# dagger 1
# rope 2
# torch 4
# total number of items: 61
dragon = {'gold coin': 50, 'ruby': 15}
inv.update(dragon)
print(inv)
# inventory:
# ruby 15
# gold coin 92
# dagger 1
# rope 2
# torch 4
# arrow 12
# total number of items: 126