首页 > 解决方案 > 遍历 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

解决方案


看起来您的大部分困惑与 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.

推荐阅读