Python3 dictionary setdefault () method
description
Python dictionary setdefault () method and get () method is similar, if the key does not already exist in the dictionary, it will be add keys and values to the default values.
grammar
setdefault () method syntax:
dict.setdefault(key, default=None)
parameter
- key - to find the key.
- default - default key when the key does not exist setup.
return value
This method has no return value.
Examples
The following example shows setdefault () method to use:
#!/usr/bin/python3 dict = {'Name': 'w3big', 'Age': 7} print ("Age 键的值为 : %s" % dict.setdefault('Age', None)) print ("Sex 键的值为 : %s" % dict.setdefault('Sex', None)) print ("新字典为:", dict)
The above example output is:
Age 键的值为 : 7 Sex 键的值为 : None 新字典为: {'Age': 7, 'Name': 'w3big', 'Sex': None}