The Dictionary 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
my_dictionary.setdefault(key, default)setdefault() Parameters
Python Dictionary setdefault() method parameters:
| Parameter | Condition | Description |
|---|---|---|
key |
Required | The key to be searched in the Dictionary |
default |
Optional | The value to be inserted if the key is not found in the dictionary. If not provided, the default value is None. |
setdefault() Return Value
Python Dictionary setdefault() method behaves differently according to parameters used:
- If the
keyis found in the dictionary,setdefault()returns the value associated with the key. - If the
keyis not found and adefaultvalue is provided,setdefault()inserts the key with the default value into the dictionary and returns thedefaultvalue. - If the
keyis not found and nodefaultvalue is provided,setdefault()inserts the key with a None value into the dictionary and returns None.
Examples
Example 1: setdefault() method when key is in the dictionary
If key is in the dictionary, the setdefault() method returns the value for key (no matter what you pass in as default, since a pair key-value exists in the dictionary!)
For example, the key is present and default is not specified:
my_dict = {'name': 'Tom', 'age': 25}
returned = my_dict.setdefault('name')
print(my_dict) # Output: {'name': 'Tom', 'age': 25}
print(returned) # Output: Tomoutput
{'name': 'Tom', 'age': 25}
TomFor example, when the key is present and default is specified, the default value is ignored:
my_dict = {'name': 'Tom', 'age': 25}
returned = my_dict.setdefault('name', 'Ryan')
print(my_dict) # Output: {'name': 'Tom', 'age': 25}
print(returned) # Output: Tomoutput
{'name': 'Tom', 'age': 25}
TomExample 2: setdefault() method when key is not in the dictionary
If key is not in the dictionary, the method inserts key with a value of default and returns default.
my_dict = {'name': 'Tom', 'age': 25}
returned = my_dict.setdefault('job', 'Developer')
print(my_dict) # Output: {'name': 'Tom', 'age': 25, 'job': 'Developer'}
print(returned) # Output: Developeroutput
{'name': 'Tom', 'age': 25, 'job': 'Developer'}
DeveloperExample 3: setdefault() method when key is not in the dictionary without default value
If key is not in the dictionary and default is not specified, the method inserts key with a value None and returns None.
my_dict = {'name': 'Tom', 'age': 25}
returned = my_dict.setdefault('job')
print(my_dict) # Output: {'name': 'Tom', 'age': 25, 'job': None}
print(returned) # Output: Noneoutput
{'name': 'Tom', 'age': 25, 'job': None}
None