[PYTHON] Memo "Chapter 5 – Dictionaries and Structuring Data"

addInventory.py

def displayInventory(inventory):
    print("Inventory:")
    item_total = 0
    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        item_total = item_total + v
    print("Total number of items: " + str(item_total))

def addToInventory(inventory, addedItems):
    # The setdefault() method is a nice shortcut to ensure that a key exists.
    for i in range(len(addedItems)):
        inventory.setdefault(addedItems[i], 0)
        inventory[addedItems[i]] = inventory[addedItems[i]] + 1
    return inventory

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

displayInventory(inv)

Recommended Posts

Memo "Chapter 5 – Dictionaries and Structuring Data"
Memo "Automate the Boring stuff -chapter5 Dictionaries and Structuring Data"
[Python] Chapter 04-06 Various data structures (creating dictionaries)
Python data structure and operation (Python learning memo ③)
[Python] Conversion memo between time data and numerical data
[Python] Chapter 04-05 Various data structures (tuple creation and features)
[Python] Chapter 04-01 Various data structures (list creation and element retrieval)
[Python] [Supplement] Chapter 04-08 Various data structures (creating and manipulating sets)
Python for Data Analysis Chapter 4
Python and ruby slice memo
Python data type summary memo
Python for Data Analysis Chapter 2
Point and Figure Data Modeling
Algebraic data types and FizzBuzz
Python for Data Analysis Chapter 3
Extract csv data and calculate