<p>关于“幻想游戏清单的列表到字典功能”的问题-第5章。用Python自动化那些无聊的东西。</p>
<pre><code># This is an illustration of the dictionaries
# This statement is just an example inventory in the form of a dictionary
inv = {'gold coin': 42, 'rope': 1}
# This statement is an example of a loot in the form of a list
dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
# This function will add each item of the list into the dictionary
def add_to_inventory(inventory, dragon_loot):
for loot in dragon_loot:
inventory.setdefault(loot, 0) # If the item in the list is not in the dictionary, then add it as a key to the dictionary - with a value of 0
inventory[loot] = inventory[loot] + 1 # Increment the value of the key by 1
return inventory
# This function will display the dictionary in the prescribed format
def display_inventory(inventory):
print('Inventory:')
total_items = 0
for k, v in inventory.items():
print(str(v) + ' ' + k)
total_items = total_items + 1
print('Total number of items: ' + str(total_items))
# This function call is to add the items in the loot to the inventory
inv = add_to_inventory(inv, dragon_loot)
# This function call will display the modified dictionary in the prescribed format
display_inventory(inv)
</code></pre>