The Python dictionary get() function returns the value of the specified key, or the default value if the value is not in the dictionary.
The setdefault()
in the Python dictionary can implement the operation of the dictionary default value. The related blog posts are as follows
python function-dictionary setting default value setdefault()python function-dictionary setting get() and setdefault() difference
dict_name.get(key,default= None)
# key:Key to set default value
# default:To return the value of key, it can be any value, such as integer, string, list, dictionary, etc.
# return:If the key in the dictionary originally has a value, then the value corresponding to the key in the dictionary is returned, if not, the value in "default" is returned.
Note: get() is just a value operation without assigning a value to the dictionary. See the following example for details:
>>> dict_name ={}>>> dict_name.get("name")>>> dict_name
{}
# Set "name" to get "wangcongying",But print dict_When name, there is no value in the dictionary
>>> dict_name.get("name","wangcongying")'wangcongying'>>> dict_name
{}
>>> dict_name["name"]="wangcongying">>> dict_name
{' name':'wangcongying'}>>> dict_name["gender"]= None
>>> dict_name
{' name':'wangcongying','gender': None}>>> dict_name.get("gender","male")>>> dict_name
{' name':'wangcongying','gender': None}>>> dict_name.get("name","julia")'wangcongying'
What get() does is the default value setting of value operation.
Recommended Posts