'Finding the total count of a key in a nested dictionary?
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')))
Solution 1:[1]
Here is a possible solution:
def totalBrought(guests, name):
broughtByPerson = 0
for food, quantity in guests[name].items():
broughtByPerson += quantity
return broughtByPerson
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Riccardo Bucco |
Solution 2 | edd313 |