Python3 Att Dictionary Setdefault
# Python3.x Python3 Dictionary setdefault() Method
[ Python3 Dictionary](#)
* * *
## Description
The Python dictionary setdefault() method is similar to the [get() method](#). If the key does not exist in the dictionary, it will add the key and set its value to the default value.
## Syntax
The syntax for the setdefault() method is:
dict.setdefault(key, default=None)
## Parameters
* key -- The key to look up.
* default -- The default value to set if the key does not exist.
## Return Value
If the key is in the dictionary, it returns the corresponding value. If the key is not in the dictionary, it inserts the key with the specified default value and returns the default value. The default value for default is None.
## Example
The following example demonstrates the usage of the setdefault() method:
## Example
#!/usr/bin/python3 tinydict = {'Name': 'Tutorial', 'Age': 7} print("Age value: %s" % tinydict.setdefault('Age', None))print("Sex value: %s" % tinydict.setdefault('Sex', None))print("New dictionary: ", tinydict)
The output of the above example is:
Age value: 7Sex value: NoneNew dictionary: {'Age': 7, 'Name': 'Tutorial', 'Sex': None}
* * Python3 Dictionary](#)
YouTip