Facebook Page Twitter Page LinkedIn Page
× Python Tutorial Python Advanced Python Resources Python Libraries

The dictionary setdefault() method is used to perform two action simultaneously. First, it checks whether the specified key exists in the dictionary or not. If the key exists then nothing is changed else the specified key is added in the dictionary with specified value.


dictionary.setdefault(key, value)


key Required. key which need to be added in the dictionary.
value Optional. value of key. default is none.

Return Value

Returns the value of the specified key in the dictionary.


In the below example, the setdefault() method to used with dictionary to insert specified key with specified value (if key is not already present in the dictionary).

MyDict = {
   'name': 'John'
#Nothing is changed as 'name' key already exists
MyDict.setdefault('name', 'Sam')

#added 'age' key with None value

#added 'city' key with 'London' value
MyDict.setdefault('city', 'London')

The output of the above code will be:

{'name': 'John'}

{'name': 'John', 'age': None}

{'name': 'John', 'age': None, 'city': 'London'}

❮ Python Dictionary Methods