Same point:
- Both are the same parameters: Dict.get (Key, Default=none), Dict.setdefault (Key, Default=none)
- If the specified key does not exist, both returns a default value of None
- If the specified key is present, even if the default value is set, the value of the specified key is returned
different points:
- When the specified key does not exist, the Dict.setdefault () method can update the dictionary by adding a key-value pair, and the Dict.get () method does not work
Example:
Dict.get (Key, Default=none)
>>>dict_1 = {'Name':'Jack'} >>>dict_1.get (' Age') #默认default为None, that is, do not return a value>>>dict_1.get (' Age','NA') #当指定的键不存在时, return the value of default ' NA ''NA'>>>dict_1.get ('Name':'Tom'#当指定的键存在时, even if the value of default is set, the value of the specified key is returned ' Jack ''Jack'>>>d{'Name':'Jack'} #dict_1中的键值对已经改变
Dict.setdefault (Key, Default=none)
>>>dict_1 = {'Name':'Jack'} >>>dict_1.setdefault (' Age') #默认default为None, that is, do not return a value>>>dict_1 #dict_1中已经增加 ' age ': The key value of None {'Name':'Jack',' Age': None}>>>dict_1.setdefault (' Age', 23#当指定的键存在时, even if the value of default is set, the value returned by the specified key is none, that is, the value is not returned>>>dict_1{'Name':'Jack',' Age': None}
Similarities and differences between Dict.get () and Dict.setdefault () in the Python dictionary