关注微信公众号(瓠悠笑软件部落),一起学习,一起摸鱼

allGuests = {'Alice': {'apples': 5, 'pretzels': 12}, 'Bob': {'ham sandwiches': 3, 'apples': 2}, 'Carol': {'cups': 3, 'apple pies': 1}}
def totalBrought(guests, item):
numBrought = 0
for k, v in guests.items():
numBrought = numBrought + v.get(item, 0)
return numBrought
print('Number of things being brought:')
print(' - Apples ' + str(totalBrought(allGuests, 'apples')))
print(' - Cups ' + str(totalBrought(allGuests, 'cups')))
print(' - Cakes ' + str(totalBrought(allGuests, 'cakes')))
print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches')))
print(' - Apple Pies ' + str(totalBrought(allGuests, 'apple pies')))
# outputs
########################################
Number of things being brought:
- Apples 7
- Cups 3
- Cakes 0
- Ham Sandwiches 3
- Apple Pies 1
########################################
dictionary 的遍历与更新
inventory = {'arrow': 12, 'gold coin': 42, 'rope': 1, 'torch': 6, 'dagger': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = {'gold coin': 42, 'rope': 1}
def displayInventory(dictionary):
print('Inventory:')
total_items = 0
for k, v in dictionary.items():
print(str(v) + ' ' + k)
total_items += v
print('Total number of items:' + str(total_items))
def addToInventory(inventory, addedItems):
for item in addedItems:
inventory.setdefault(item, 0)
new_count = inventory.get(item) + 1
inventory[item] = new_count
return inventory
displayInventory(inv)
added_inv = addToInventory(inv, dragonLoot)
displayInventory(added_inv)
本文探讨了如何遍历和更新Python中的嵌套字典,适合正在学习Python字典操作的读者。
8309

被折叠的 条评论
为什么被折叠?



