Latest web development tutorials

Python dictionary (Dictionary) setdefault () method


Python dictionary (Dictionary) setdefault () function and get () method is similar, if the key does not already exist in the dictionary, it will be add keys and values to the default values.


setdefault () method syntax:

dict.setdefault(key, default=None)


  • key - to find the key.
  • default - default key when the key does not exist setup.

return value

This method has no return value.


The following example shows setdefault () function to use:


dict = {'Name': 'Zara', 'Age': 7}

print "Value : %s" %  dict.setdefault('Age', None)
print "Value : %s" %  dict.setdefault('Sex', None)

The above example output is:

Value : 7
Value : None