-1
dict2 = {'Name': 'sandeep', 'Age': 15, 'Class': '11th', 'school': 'GSBV'}
print(dict2)
if 'collage' in dict2.keys(): print(dict2['collage'])
else: print('no key found in dict')
print(dict2.setdefault('collage', 'this key do not exist in dict'))
if 'collage' in dict2.keys(): print(dict2['collage'])
else: print('no key found in dict')

OUTPUT

no key found in dict
this key do not exist in dict
this key do not exist in dict

It does not print

no key found in dict

but instead, it prints

this key do not exist in dict

in the last line, why is my program having this behavior?

  • this code works correctly, What do you expect? when use `setdefault` if the key doesn't exist add a key with the default value and in the second if `college` exist in the dict and doesn't print : `no key found in dict` – I'mahdi Aug 26 '22 at 18:06
  • The [docs](https://docs.python.org/3/library/stdtypes.html#dict.setdefault) make it pretty clear what `dict.setdefault` does. Did you read the documentation? That should be the first place you look when you have any questions about a function – Pranav Hosangadi Aug 26 '22 at 18:07
  • 1
    [If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.](https://docs.python.org/3.10/library/stdtypes.html#dict.setdefault) – rdas Aug 26 '22 at 18:07
  • You can use `print(dict2)` after `dict2.setdefault` and see what exist in `dict2` – I'mahdi Aug 26 '22 at 18:08
  • don't put code after `:` but in next line - your code is unreadable. See more: [PEP 8 -- Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/) – furas Aug 26 '22 at 20:12

1 Answers1

0

setdefault is exactly what it sounds like. It sets the default value for a key in the dictionary. The first parameter given to the method is the key you want to set, and the second parameter is the default value. So when you run setdefault on a dict that already has a value for the key, it simply ignores it. Otherwise it will set the key to the default value.

For example:

>>> a = dict()
>>> a.setdefault('key', 'value')
'value'
>>> a.setdefault('key', 'othervalue')
'value'
>>> a
{'key': 'value'}

As you can see when the dict was empty calling setdefault added the key, value pair and returned the value, but when called again it didn't change the value to othervalue because a value already existed.

This is convenient especially when you are dealing with iterable types.

For example:

>>> a = {}
>>> for char in ["A", "B", "C"]:
...     for num in [1, 2, 3]:
...         lst = a.setdefault(char, [])
...         lst.append(num)
...
>>> a
{'A': [1, 2, 3], 'B': [1, 2, 3], 'C': [1, 2, 3]}

Without setdefault It would be neccessary to write a conditional statement that checked on every iteration if the key had already been set or not.

Alexander
  • 16,091
  • 5
  • 13
  • 29