在嵌套字典中查找键的总数?

Finding the total count of a key in a nested dictionary?

这是从 http://automatetheboringstuff.com/2e/chapter5/ 中修改的练习。他们原来的例子要求找出所有客人带来的物品总数,例如每个人

带来的'apples'的总数

我想弄清楚如何使函数 return 每个人带来的物品总数,这就是我想出的代码。 它有效,但是

broughtByPerson += v.get('apples',0)

部分似乎可以简化。如果有 100 个不同的项目,如果不为每个不同的项目编写以上行,代码会是什么样子?

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

def totalBrought(guests, names): 
    broughtByPerson = 0             
    for k,v in guests.items():      
        if k == names:              
            broughtByPerson += v.get('apples',0)  
            broughtByPerson += v.get('pretzels',0)
            broughtByPerson += v.get('ham sandwiches',0)
            broughtByPerson += v.get('cups',0)
            broughtByPerson += v.get('apple pies',0)
    return broughtByPerson

print('Alice brought: ' + str(totalBrought(allGuests, 'Alice')))
print('Bob brought: ' + str(totalBrought(allGuests, 'Bob')))
print('Carol brought: ' + str(totalBrought(allGuests, 'Carol')))

您可以只对内部字典的值求和:

def totalBrought(guests, name):
    return sum(guests[name].values())

这是一个可能的解决方案:

def totalBrought(guests, name):
    broughtByPerson = 0
    for food, quantity in guests[name].items():
        broughtByPerson += quantity
    return broughtByPerson

您可以使用 DataDict。先安装 ndicts

pip install ndicts

然后:

from ndicts.ndicts import DataDict

all_guests = {
    'Alice': {'apples': 5, 'pretzels': 12},
    'Bob': {'ham sandwiches': 3, 'apples': 2},
    'Carol': {'cups': 3, 'apple pies': 1}
}
dd = DataDict(all_guests)

apples = dd.extract["", "apples"].total()

其他解决方案看起来不错,但这应该更通用并且适用于任何深度的任何嵌套字典。