python - 遍历 Python 中的嵌套字典
问题描述
我真的很困惑。这是我目前正在阅读的一本书。
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')))
这本书在解释它方面做得不好(至少对我而言)。我一直对这个程序感到困惑,因为没有真正给出解释。
对我来说最令人困惑的部分是:
def totalBrought(guests, item):
numBrought = 0
for k, v in guests.items():
numBrought = numBrought + v.get(item, 0)
return numBrought
这是输出:
Number of things being brought:
- Apples 7
- Cups 3
- Cakes 0
- Ham Sandwiches 3
- Apple Pies 1
解决方案
看起来您的大部分困惑与 python字典和键值对有关。
这里令人困惑的部分是allGuests
字典是嵌套的。也就是说,与每个关键元素关联的值本身就是一个字典。因此,例如,'Alice'
在高级字典中查找 Key 将返回 dictionary {'apples': 5, 'pretzels': 12}
。如果您想知道 Alice 买了多少苹果,您必须'apple'
在嵌套字典中查找键(返回 5)。这就是这本书所做的v.get(item, 0)
。您提到的代码可以这样解释:
def totalBrought(guests, item): #Remember, guests is a dictionary
numBrought = 0 #initialize the total number of items found to 0
for k, v in guests.items(): #For Every Key (k) / Value (v) pair
#in the dictionary (iterating by keys)
#Get the number of item objects bought.
#Note that v.get() is searching the nested dictionary by key value.
numBrought = numBrought + v.get(item, 0)
return numBrought #Return the number of item objects in dictionary.
推荐阅读
- linux - 显示在后台启动的进程的 shell 脚本
- go - 无论对象类型如何,如何拆分对象?
- c++ - 在 OpenCV 中与屏幕捕获一起使用的函数 matchTemplate
- javascript - 如何防止带有网络扩展的历史条目?
- python - 来自修改后的 Google 提供的模板的 Cloud Dataflow 任务中的自动缩放性能问题
- android - 如何将自定义坐标传递给地图框导航启动器?
- logstash-grok - Grok 表达式解析日志数据
- c - 在 C 中为多个进程之间的进程间通信创建管道
- vim - 如何添加键盘快捷键来激活/禁用 VSCode 扩展?
- node.js - Nodejs Handlebars Dynamic Partials 使用