Att Dictionary Setdefault
# Python2.x Python Dictionary setdefault() Method
[ Python Dictionary](#)
* * *
## Description
The Python dictionary setdefault() function is similar to the [get() method](#). If the key does not exist in the dictionary, it will add the key and set the 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 dictionary contains the given key, it returns the value corresponding to that key; otherwise, it returns the value set for that key.
## Example
The following example demonstrates the usage of the setdefault() function:
## Example (Python 2.0+)
#!/usr/bin/python# -*- coding: UTF-8 -*-tinydict = {'tutorial': '', 'google': 'Google Search'} print"Value : %s" % tinydict.setdefault('tutorial', None)print"Value : %s" % tinydict.setdefault('Taobao', 'Taobao')
The output of the above example is:
Value : Value : Taobao
[ Python Dictionary](#)
YouTip