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

发布于 2025-01-10 07:25:47 字数 1172 浏览 0 评论 0原文

这是一个修改后的练习,取自 http://automatetheboringstuff.com/2e/chapter5/。他们最初的示例要求查找所有客人带来的物品总数,例如每个人带来的“苹果”总数

我想弄清楚如何使该函数返回每个人带来的物品总数,这是我来的代码跟上。 它有效,但该

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')))

This is a modified exercise taken from http://automatetheboringstuff.com/2e/chapter5/. Their original example asks to find the total items brought from all guests, such as the total number of 'apples' brought by everybody

I wanted to figure how to make the function return the total items brought by each person and this is the code I came up with.
It works, but the

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

part seems like it could be simplified. If there was 100 different items, how would the code look without writing the above line for every different item?

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')))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

机场等船 2025-01-17 07:25:47

您可以将内部字典的值相加:

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

You can just sum the values of the inner dictionary:

def totalBrought(guests, name):
    return sum(guests[name].values())
朮生 2025-01-17 07:25:47

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

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

Here is a possible solution:

def totalBrought(guests, name):
    broughtByPerson = 0
    for food, quantity in guests[name].items():
        broughtByPerson += quantity
    return broughtByPerson
彼岸花似海 2025-01-17 07:25:47

您可以使用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()

其他解决方案看起来很棒,但这应该更通用,并且可以与任何深度的任何嵌套字典一起使用。

You can use a DataDict. Install ndicts first.

pip install ndicts

Then:

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()

Other solutions look great but this should be more general and work with any nested dictionary of any depth.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文