Python Tutorial Python Advanced Python References Python Libraries

Python Dictionary - setdefault() Method



The Python 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.

Syntax

dictionary.setdefault(key, value)

Parameters

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.

Example:

In the example below, 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')
print(MyDict)

#added 'age' key with None value
MyDict.setdefault('age')
print(MyDict)

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

The output of the above code will be:

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

❮ Python Dictionary Methods

5