Returns the value for key if exists, else inserts it
Usage
The setdefault()
method returns the value for key if key is in the dictionary. If not, it inserts key with a value of default and returns default.
Syntax
dictionary.setdefault(key,default)
Parameter | Condition | Description |
key | Required | Any key you want to return value for |
default | Optional | A value to insert if the specified key is not found. Default value is None. |
Basic Example
setdefault()
method is generally used to insert a key with a default value.
# Insert a key 'job' with default value 'Dev'
D = {'name': 'Bob', 'age': 25}
v = D.setdefault('job', 'Dev')
print(D)
# Prints {'job': 'Dev', 'age': 25, 'name': 'Bob'}
print(v)
# Prints Dev
setdefault() Method Scenarios
The method’s output depends on input parameters. Here are three scenarios for different input parameters.
Key Present
If key is in the dictionary, the method returns the value for key (no matter what you pass in as default)
# without default specified
D = {'name': 'Bob', 'age': 25}
v = D.setdefault('name')
print(v)
# Prints Bob
# with default specified
D = {'name': 'Bob', 'age': 25}
v = D.setdefault('name', 'Max')
print(v)
# Prints Bob
Key Absent, Default Specified
If key is not in the dictionary, the method inserts key with a value of default and returns default.
D = {'name': 'Bob', 'age': 25}
v = D.setdefault('job', 'Dev')
print(D)
# Prints {'job': 'Dev', 'age': 25, 'name': 'Bob'}
print(v)
# Prints Dev
Key Absent, Default Not Specified
If key is not in the dictionary and default is not specified, the method inserts key with a value None and returns None.
D = {'name': 'Bob', 'age': 25}
v = D.setdefault('job')
print(D)
# Prints {'job': None, 'age': 25, 'name': 'Bob'}
print(v)
# Prints None