Usage and function of the understanding setdefault

Usage and function of the understanding setdefault

dict.setdefault(key, default=None)

Function:
If the key does not exist in the dictionary, it will add the value of the key and default is set to the default value of the key, if the key exists in the dictionary, read out the key corresponding to the original value, the value is not default coverage value of the already existing key.

Parameters:
Key ---- To find the key to
the default value used to set the key default ----- looking for does not exist

examples of use: (use the following method is my understanding of the process setdefault function)
method: to dictionary key assignment does not exist in the default value None

>>> ExsampleDict={"Exist":"Elle"}
>>> Res=ExsampleDict.setdefault("NotExist",)
>>> print ExsampleDict
{'NotExist': None, 'Exist': 'Elle'}

Method two: reading out the key corresponding to the value of the dictionary present in

 
>>> ExsampleDict={"Exist":"Elle"}
>>> Res=ExsampleDict.setdefault("Exist","NotReplace")
>>> print Res
Elle
>>> type(Res)
<type 'str'>
>>> print ExsampleDict["Exist"]
Elle
>>> 
 

Method three: to the keys not in the dictionary assignment for the "Replace"

 
>>> ExsampleDict={"Exist":"Elle"}
>>> Res=ExsampleDict.setdefault("NotExist","Replace")
>>> print Res
Replace
>>> type(Res)
<type 'str'>
>>> print ExsampleDict
{'NotExist': 'Replace', 'Exist': 'Elle'}
>>> 
 

Method four: to the keys not in the dictionary as a list assignment

 
>>> ExsampleDict={"Exist":"Elle"}
>>> Res=ExsampleDict.setdefault("NotExist",[])
>>> print Res
[]
>>> type(Res)
<type 'list'>
>>> Res=ExsampleDict.setdefault("NotExist",[]).append("Replace")
>>> print ExsampleDict
{'NotExist': ['Replace'], 'Exist': 'Elle'}
>>> 
 

Method five: to key assignment not in the dictionary as a dictionary

 
>>> ExsampleDict={"Exist":"Elle"}
>>> ExsampleDict.setdefault("NotExist",{})
{}
>>> ExsampleDict={"Exist":"Elle"}
>>> Res=ExsampleDict.setdefault("NotExist",{})
>>> print Res
{}
>>> type(Res)
<type 'dict'>
>>> Res=ExsampleDict.setdefault("NotExist",{})["Insert"]="InsertValue"
>>> print ExsampleDict
{'NotExist': {'Insert': 'InsertValue'}, 'Exist': 'Elle'}
>>> 

Text content Source: https://www.cnblogs.com/elleblog/p/7533413.html

Guess you like

Origin www.cnblogs.com/suguangti/p/11525440.html