Python Dictionary Setdefault() Method



Python dictionary method setdefault() is alike to get(), yet will put dict[key]=default if input is not previously indict. In Python vocabulary, setdefault() method arrivals the value of a key (if the key is in a dictionary). If not, it introduces a key with a charge to the dictionary. ... key – Key to being looked at in the dictionary. default_value (optional) – Key with a charge default_value is inserted into the vocabulary if the key is not in the dictionary.


Following is the syntax for setdefault() method:

dict.setdefault(key, default=None)


  • key - This is the key to be searched.
  • default - This is the Value to be returned in case key is not found.

Return Value

This method returns the key-value available in the dictionary and if the given key is not available then it will return provided default value.


The following example shows the usage of setdefault() method.


dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" %  dict.setdefault('Age', None)
print "Value : %s" %  dict.setdefault('Sex', None)

When we run the above program, it produces the following result:

Value : 7
Value : None

Here at Intellinuts, we have created a complete Python tutorial for Beginners to get started in Python.