Apr-21-2019, 09:22 AM
I rewrote the following exercise:
I can't understand why shall I need the setdefault() method? Python does understand in idle that when I add a new key to a dictionary in the shell, for example, output and input in my shell:
I need to ask since it required quite a long time to get what was wrong.
allGuests = {'Alice': {'apples': 5, 'pretzels': 12}, 'Bob': {'ham sandwiches': 3, 'apples': 2}, 'Carol': {'cups': 3, 'apple pies': 1}} def totalBrought(guests, item): numBrought = 0 for k, v in guests.items(): numBrought = numBrought + v.get(item, 0) return numBrought print('Number of things being brought:') print(' - Apples ' + str(totalBrought(allGuests, 'apples'))) print(' - Cups ' + str(totalBrought(allGuests, 'cups'))) print(' - Cakes ' + str(totalBrought(allGuests, 'cakes'))) print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches'))) print(' - Apple Pies ' + str(totalBrought(allGuests, 'apple pies')))to:
allGuests = {'Alice': {'apples': 5, 'pretzels': 12}, 'Bob': {'ham sandwiches': 3, 'apples': 2}, 'Carol': {'cups': 3, 'apple pies': 1}} def whatIsBrought(allGuest): objects={} for guest in allGuests.values(): for k, v in guest.items(): objects.setdefault(k,0) #why do I need that? objects[k] += v return objects objects = whatIsBrought(allGuests) print(objects)to minimize the printing and iterating automatically over all objects being brought by all the guests.
I can't understand why shall I need the setdefault() method? Python does understand in idle that when I add a new key to a dictionary in the shell, for example, output and input in my shell:
Output:Python 3.7.2 (v3.7.2:9a3ffc0492, Dec 24 2018, 02:44:43)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license()" for more information.
>>> children={}
>>> children['jessie']='noisy'
>>> children['patrick']='irritatinng'
>>> children
{'jessie': 'noisy', 'patrick': 'irritatinng'}
>>>
I need to ask since it required quite a long time to get what was wrong.