Dictionary setdefault() method Python

The Python dictionary setdefault() method is similar to get() method.With setdefault() we can get the value of the item using the key.This method can accept one or two arguments.

Link: Dictionary get() method

If we pass only one argument it should be the key of the item.However,if the argument passed does not match any key the method return nothing.

>>> d={ 23:456 , 'New':'text' , 'Soar':'SOAR' , 345:890}
>>> d.setdefault( 23 )
456
>>> d.setdefault( 'Soar' )
>>> 'SOAR'
>>> d.get( 345 )
890
>>> #Passing no argument
>>> d.setdefault()
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    d.setdefault()
TypeError: setdefault expected at least 1 arguments, got 0
>>> #Passing wrong key as argument
>>> d.setdefault( 256 ) #returns nothing

Well get() and setdefault() methods are pretty much similar,they return the value of the item.

The only time you will notice the difference between get() and setdefault() is when you pass two arguments.


Passing two arguments to setdefault()

As stated earlier we can also pass two arguments to setdefault().Here the first argument being the key of the value and the second argument can be any value.

Now the little twist here being that if you pass the correct key as the first argument then the second argument has no purpose and the method return the value of the key.But if you pass a non-existent key then the method returns the second argument as the output.And note the non-existent key and the second argument is added as an item to the dictionary.

>>> d={ 23:456 , 'New':'text' , 'Soar':'SOAR' , 345:890}
>>> d.setdefault( 'New'  , 'Norm' )
'text'
>>> #passing non-existent key
>>> d.setdefault( 'Norm' , 'Hamster' )
'Hamster'
>>> d
{23: 456, 'New': 'text', 'Soar': 'SOAR', 345: 890, 256: None, 'Norm': 'Hamster'}
>>> # {'Norm':'Hamster'} is added as a new item!!!

Difference between get() and setdefault()

The get() method can also accept two arguments,and behave much like the setdefault().This means if we pass a correct key as the first argument then the second argument has no purpose except that get() returns it as the output.

If we however pass a non-existent key as the first argument then the get() returns the second argument as the output but here the first and second argument is not added as a new item,they are discarded.But as you can see in case of setdefault() it adds them as a new item.

>>> d1={ 12:34 , 56:78 , 9:10 , 11:12 }
>>> d1.get( 12 )
34
>>> d1.setdefault( 12 )
34
>>> #Passing non-existent key
>>> d1.get( 'Text' , 'Value' )
'Value'
>>> d1 
{12: 34, 56: 78, 9: 10, 11: 12}
>>> d1.setdefault( 'text' , 'value')
'value'
>>> d1
{12: 34, 56: 78, 9: 10, 11: 12, 'text': 'value'}

This is the difference between get() and setdefault() method.



Leave a Reply

Your email address will not be published. Required fields are marked *