Python Dictionary setdefault() Method

Python 字典Python Dictionary


Description

The Python dictionary setdefault() function andget() methodSimilar, if the key does not exist in the dictionary, the key will be added and the value set to the default value.

Syntax

setdefault() method syntax:

dict.setdefault(key, default=None)

Parameters

  • key -- The key to search for.
  • default -- The default value to set when the key does not exist.

Return Value

If the dictionary contains the given key, return the value corresponding to that key, otherwise return 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 = {'example': 'Example', 'google': 'Google Search'} print "Value : %s" % tinydict.setdefault('example', None) print "Value : %s" % tinydict.setdefault('Taobao', 'Taobao')

The output of the above example is:

Value : Example
Value : 淘宝

Python 字典Python Dictionary

Other Extensions