Python dictionary setdefault() Method
Advertisements
Description
The method setdefault() is similar to get(), but will set dict[key]=default if key is not already in dict.
Syntax
Following is the syntax for setdefault() method
dict.setdefault(key, default=None)
Parameters
key -- This is the key be searched.
default -- This is the Value to be returned in case key is not found.
Return Value
This method does not return any value.
Example
The following example shows the usage of setdefault() method.
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.setdefault('Age', None)
print "Value : %s" % dict.setdefault('Sex', None)
Let us compile and run the above program, this will produce the following result:
Value : 7 Value : None