查找嵌套字典中键的总数?
这是一个修改后的练习,取自 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将内部字典的值相加:
You can just sum the values of the inner dictionary:
这是一个可能的解决方案:
Here is a possible solution:
您可以使用
DataDict
。首先安装 ndicts 。然后:
其他解决方案看起来很棒,但这应该更通用,并且可以与任何深度的任何嵌套字典一起使用。
You can use a
DataDict
. Install ndicts first.Then:
Other solutions look great but this should be more general and work with any nested dictionary of any depth.