When learning the python dictionary operation method, I feel that the setdefault () method is more difficult to understand than other basic operation methods in the dictionary. so I want to summarize the following, the following article describes the setdefault () method of the dictionary in Python. you can refer to it for reference. let's take a look at it. When learning the python dictionary operation method, I feel that the setdefault () method is more difficult to understand than other basic operation methods in the dictionary. so I want to summarize the following, the following article describes the setdefault () method of the dictionary in Python. you can refer to it for reference. let's take a look at it.
Preface
As mentioned in the basic knowledge of python, the dictionary is a variable data type, and its parameters are key-pair values. The setdefault () method is similar to the get () method of the dictionary in some places, and the value corresponding to the given key can be obtained. However, the setdefault () method can set a value for a given key if the dictionary does not contain a given key.
The Python dictionary's setdefault method prototype is as follows:
dict.setdefault(key, default=None)
If the given key is in the dictionary, this value is returned. if it is not in the dictionary, the key is inserted into the dictionary and the value is set to the specified default parameter. the default value of default is None.
Using the setdefault method is equivalent to the following operations:
if key in dict: reurn dict[key]else: dict[key] = default return default
This method is similar to the get method of the dictionary, but there are some differences.dict.get
Anddict.setdefault
The method returns this value when the key exists in the dictionary. if the key is not in the dictionary, the default value is also returned. The difference between the two methods is that when the key is not in the dictionary, the setdefault method inserts the default key value in the dictionary and returns the value. The get method only returns the default value, but 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}
For more articles about the setdefault () method of the dictionary in Python, refer to the PHP Chinese website!