Python Dictionary setdefault() Method
The setdefault() method returns the value of a specified key. If the key doesn’t exist, it inserts the key with a specified default value and returns that value.
Syntax
dict.setdefault(key, default_value)
Parameters
key: The key to look for in the dictionary.
default_value (Optional): The value to insert if the key is not found. The default is None.
Return Value
The value of the key if it exists in the dictionary.
If the key doesn’t exist, it inserts the key with the default_value and returns the default_value.
Example 1: Using setdefault() with an existing key
person = {"name": "James Bond", "age": 37}
# Key exists, returns the value
name = person.setdefault("name", "Unknown")
print(name) # Output: James Bond
Example 2: Using setdefault() with a non-existing key
person = {"name": "James Bond", "age": 37}
# Key doesn't exist, inserts it with the default value and returns default value
city = person.setdefault("city", "Unknown")
print(city)
print(person)
Output:
Unknown
{'name': 'James Bond', 'age': 37, 'city': 'Unknown'}
Example 3: Using setdefault() without a default a value
person = {"name": "James Bond", "age": 37}
# Key doesn't exist, inserts it with None as the default value and returns None
city = person.setdefault("city")
print(city)
print(person)
Output:
None
{'name': 'James Bond', 'age': 37, 'city': None}