遍历Python中的嵌套字典

时间:2019-03-01 17:48:26

标签: 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

2 个答案:

答案 0 :(得分:1)

看起来您的大部分困惑与python dictionaries and key value pairs有关。

这里令人困惑的部分是allGuests字典是嵌套的。这就是说,与每个键元素关联的值本身就是字典。因此,例如,在高级词典中查找键'Alice'将返回词典{'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.

答案 1 :(得分:0)

Quote9963让我帮助您

首先,我在示例代码中添加了一些注释:

# In this code, we have a dictionary 'allGuests' that contains: 
#    "A guest (string) " and another dictionary 
#    (let call this dictionary as "bag" just for help ):

# So, we have:
# - Alice, another dictionary 
# - Bob, another dictionary
# - Carol, another dictionary

# Inside of Alice's bag we have: 'apples': 5, 'pretzels': 12
# Inside of Bob's bag we have: 'ham sandwiches': 3, 'apples': 2
# Inside of Carol's bag we have: 'cups': 3, 'apple pies': 1

# "bag"  is a "virtual name"to help you understand, but it is just another dictionary.    

allGuests = {'Alice': {'apples': 5, 'pretzels': 12},
'Bob': {'ham sandwiches': 3, 'apples': 2},
'Carol': {'cups': 3, 'apple pies': 1}}

# This method you pass the dictionary and the item that you are looking for.
def totalBrought(guests, item):
  numBrought = 0

  #'As a dictionary I can iterate in all elements of my dict using ".items()"'
  for k, v in guests.items():
    # I can get a element inside of my dictionary using ".get()"
    numBrought = numBrought + v.get(item, 0)
  return numBrought

print('\nNumber 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')))

print('\nMore information about python Dictionary object you can found here:')
print('https://www.w3schools.com/python/python_dictionaries.asp')

让我得到您要打印的第一个项目,以使其变得更容易:

print(' - Apples         ' + str(totalBrought(allGuests, 'apples')))

我们正在通过字典totalBrought和要查找的项目“ allGuests调用'方法'apples

在方法totalBrought内,我们有“ for k, v in guests.items()”用于在每次迭代的allGuest中进行迭代,'k'分别接收来宾名称和'v' 我们将昵称称为“ bag”的字典。

最后,在循环内,我们使用'v.get(item, 0)'并增加numBrought的数量来获得项目

totalBroughtallGuests之间逐行传递:

  1. numBrought 获得了 0
  2. 开始apples
  3. [对于迭代0] K 收到了 Alice
  4. [对于迭代0] V 收到了for k, v in guests.items():的“袋子”
  5. [对于迭代0] {'apples': 5, 'pretzels': 12}返回了 5
  6. [对于迭代0] numBrought = 0 + 5
  7. [对于迭代1] K 收到了 Bob
  8. [对于迭代1] V 收到了v.get(item, 0)的“袋子”
  9. [对于迭代1] {'ham sandwiches': 3, 'apples': 2},返回了 2
  10. [对于迭代1] numBrought = 5 + 2
  11. [对于迭代2] K 收到了 Carol
  12. [对于迭代2] V 收到了v.get(item, 0)的“袋子”
  13. [对于迭代2] {'cups': 3, 'apple pies': 1}返回了 0
  14. [对于迭代2] numBrought = 7 + 0
  15. 已结束v.get(item, 0)
  16. 返回 numBrought