In this section, we will learn what the Dictionary setdefault() method is and how to use it in Python.
What is Dictionary setdefault() Method in Python?
The Python Dictionary setdefault() method is used for two cases:
- First, it is used to get the value of a key that we put as the argument of this method.
- Second: if the specified key was not in the target dictionary, then this method will add the key as a new entry to the dictionary.
Python Dictionary setdefault() Method Syntax:
dictionary.setdefault(key, value)
Dictionary setdefault() Method Parameter:
The method takes two arguments:
- The first argument is the key we want to either get its value from the target dictionary or set it as a new key in there.
- The second argument, which is optional, will be used as the value for the specified key (if that key is to be added to the dictionary). This value is optional and if ignored, the value None will be set for the key.
Dictionary setdefault() Method Return Value
The return value of this method is the value assigned to the specified key (if the key is already set in the target dictionary) or the second argument of this method (if the key is about to be added to the dictionary).
Example: using python dictionary setdefault() method
dictionary = { "name":"John", "lastName": "Doe", "age": 200, } result = dictionary.setdefault("email","[email protected]") print(result);
Output:
[email protected]