Home > database >  Finding the total count of a key in a nested dictionary?
Finding the total count of a key in a nested dictionary?

Time:02-27

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

CodePudding user response:

You can just sum the values of the inner dictionary:

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

CodePudding user response:

Here is a possible solution:

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