Python dictionary setdefault() method
Python Dictionary setdefault() Method
Description
Python The dictionary method setdefault() is similar to the get() method, but if key is not in the dictionary, it sets dict[key] = default.
Syntax
The syntax of the setdefault() method is as follows:
dict.setdefault(key, default=None)
Parameters
- key − This is the key to search for.
-
default − The default value to return if the key is not found.
Return Value
This method returns the available key values in the dictionary, or the provided default value if the given key is not available.
Example
The following example shows the usage of the setdefault() method.
dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.setdefault('Age', None)
print "Value : %s" % dict.setdefault('Sex', None)
When we run the above program, it produces the following output –
Value : 7
Value : None