In learning the Python dictionary operation Method, feel SetDefault () method, more difficult to understand than the dictionary of the other basic methods of understanding more students, so think to summarize the following, this article mainly introduces you to the Python Dictionary SetDefault () method, Need friends can reference, below to see together.
Objective
As mentioned in Python basics, a dictionary is a mutable data type whose arguments are key-pair values. The SetDefault () method and The Get () method of the dictionary are more similar in some places and can be given a value corresponding to the specified key. However, the SetDefault () method can set the corresponding value for a given key in the case where the dictionary does not contain a given key.
The SetDefault method prototype for the Python dictionary is as follows:
Dict.setdefault (Key, Default=none)
If the given key returns the value in the dictionary, if it is not in the dictionary, the key is inserted into the dictionary and the value is set to the specified default parameter, and the default value of default is None.
Using the SetDefault method corresponds to the following:
If key in Dict:reurn Dict[key]else:dict[key] = default return default
This method is somewhat similar to the Get method of the dictionary, but there are some differences. dict.get
and dict.setdefault
methods can return this value when key is present in the dictionary, and can return the default value when key is not in the dictionary. The difference between the two methods is that when key is not in the dictionary, the SetDefault method inserts the default key value in the dictionary and returns it, and the Get method returns only the default value and does not insert a new key into the dictionary.
Example:
>>> DCT = {}>>> dct{}>>> dct["name"] = "Huoty" >>> dct{' name ': ' Huoty '}>>> Dct.setdefault ("name", "Esenich") ' Huoty ' >>> dct{' name ': ' Huoty '}>>> dct.setdefault ("FName", " Esenich ") ' Esenich ' >>> dct{' name ': ' Huoty ', ' fname ': ' Esenich '}>>> dct.setdefault (" addr ") >> > dct{' name ': ' Huoty ', ' fname ': ' Esenich ', ' addr ': none}>>> dct.get ("name", "xxx") ' Huoty ' >>> dct{' Name ': ' Huoty ', ' fname ': ' Esenich ', ' addr ': none}>>> dct.get ("Age") >>> dct{' name ': ' Huoty ', ' fname ': ' Esenich ', ' addr ': none}>>> dct.get ("Age", 2) 2>>> dct{' name ': ' Huoty ', ' fname ': ' Esenich ', ' addr ': None }