Python Forum
Why do we need setdefault() method for dictionnary? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Why do we need setdefault() method for dictionnary? (/thread-17708.html)



Why do we need setdefault() method for dictionnary? - DJ_Qu - Apr-21-2019

I rewrote the following exercise:

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.


RE: Why do we need setdefault() method for dictionnary? - Gribouillis - Apr-21-2019

If k is already a key in objects, the line objects.setdefault(k,0) does nothing. If k is not already a key, it acts like objects[k] = 0. One could replace this line with
if k not in objects:
    objects[k] = 0
It is necessary to ensure that k is already in objects because the line objects[k] += v wouldn't work if k was not already a key.


RE: Why do we need setdefault() method for dictionnary? - DJ_Qu - Apr-21-2019

I get that... But why does it work in the shell?

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


RE: Why do we need setdefault() method for dictionnary? - Gribouillis - Apr-21-2019

It works with = but not with +=
>>> objects = {}
>>> objects['apples'] += 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'apples'