The Python dictionary SetDefault () function is similar to the Get () method, and if the key does not exist in the dictionary, the key is added and the value is set to the default value.
Dict.setdefault (Key, Default=none)
- Key--The value of the lookup.
- Default-key is not present, set the defaults.
If the dictionary contains a given key, the value corresponding to the key is returned, otherwise the value set for the key is returned.
The following example shows how the SetDefault () method is used:
Dict = {' Name ': ' Runoob ', ' Age ': 7}print ("The value of age key is:%s"% dict.setdefault (' age ', None)) print ("The value of the Sex key is:%s"% Dict.setdefault (' Sex ', None)) print ("New Dictionary:", Dict) "" "The value of the age key is: The value of the 7Sex key is: None The new dictionary is: {' age ': 7, ' Name ': ' Runoob ', ' Sex ': None} "" "
Python3 dictionary SetDefault () method