Python3 Dictionary setdefault() Method

Python3 字典Python3 Dictionary


Description

Python dictionary setdefault() method andget() methodare similar. If the key is not in the dictionary, the key will be added and its value set to the default value.

Syntax

setdefault() method syntax:

dict.setdefault(key, default=None)

Parameters

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

Return Value

If the key is in the dictionary, return its corresponding value. If the key is not in the dictionary, insert the key with the default value default, and return default. The default value of default is None.

Example

The following example demonstrates how to use the setdefault() method:

Example

#!/usr/bin/python3 tinydict = {'Name': 'Example', 'Age': 7} print ("Age key value is: %s" % tinydict.setdefault('Age', None)) print ("Sex key value is: %s" % tinydict.setdefault('Sex', None)) print ("The new dictionary is:", tinydict)

The output of the above example is:

Age 键的值为 : 7
Sex 键的值为 : None
新字典为: {'Age': 7, 'Name': 'Example', 'Sex': None}

Python3 字典Python3 Dictionary

Other Extensions