Welcome to follow Me blog: Cloud Dreamer
Describe
The Python Dictionary SetDefault () method is similar to the Get () method, and if the key does not already exist in the dictionary, the key is added and the value is set to the default value.
Grammar
dict.setdefault(key, default=None)
Parameters
- Key--the keyword to find
- Default--When the key does not exist, set the defaults for the key value
return value
If key is in the dictionary, the corresponding value is returned. If it is not in the dictionary, insert key and set the default value defaults, and return to default, which defaults to None.
Instance
Example code:
#!/usr/bin/python3dict= {‘Name‘‘Runoob‘‘Age‘7}print ("Age 键的值为 : %s"% dict.setdefault(‘Age‘None))print ("Sex 键的值为 : %s"% dict.setdefault(‘Sex‘None))print ("新字典为:"dict)
Output:
7None新字典为: {‘Age‘7‘Name‘‘Runoob‘‘Sex‘None}
SetDefault () Python