Python Forum
Why do we need setdefault() method for dictionnary?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why do we need setdefault() method for dictionnary?
#1
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.
Reply
#2
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.
Reply
#3
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'}
>>>
Reply
#4
It works with = but not with +=
>>> objects = {}
>>> objects['apples'] += 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'apples'
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Dictionnary indexing error Ander 6 1,833 Sep-10-2021, 12:22 PM
Last Post: Ander
  python dictionnary Omar_Yatim 3 2,754 Dec-08-2019, 05:12 AM
Last Post: scidam
  Dictionnary brackets issue Reldaing 1 1,784 Nov-10-2019, 11:54 PM
Last Post: ichabod801
  Access to the elements of a dictionnary Reims 1 1,603 Oct-02-2019, 12:48 PM
Last Post: SheeppOSU
  from Json Time Serie file to python dictionnary Reims 1 1,989 Sep-11-2019, 08:17 AM
Last Post: DeaD_EyE
  convert a json file to a python dictionnary of array Reims 2 2,205 Sep-10-2019, 01:08 PM
Last Post: Reims
  dictionnary lateublegende 1 2,417 Apr-29-2019, 09:10 PM
Last Post: Yoriz
  Json dictionnary on Redis katsu707 1 2,410 Dec-04-2018, 11:59 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020