setdefault()

The syntax of setdefault() is as follows:

dict.setdefault(key1, default=None)  

key1 -- This is key to be searched.

Default -- if key1 is not found, then the message will be returned and added to the dictionary. Let's see the following example:

 >>> port1.setdefault(23, "Unknown")
'Telnet'
>>> port1
{80: 'http', 22: 'SSH', 23: 'Telnet'}
>>> port1.setdefault(19, "Unknown")
'Unknown'
>>> port1
{80: 'http', 19: 'Unknown', 22: 'SSH', 23: 'Telnet'}

If the message has been not been set, then it returns and adds a default value, None. See the following example:

 >>> port1.setdefault(18)
>>> port1
{80: 'http', 18: None, 19: 'Unknown', 22: 'SSH', 23: 'Telnet'}
>>>

To avoid KeyError, we can use the get() method, but we can add one more check to avoid KeyError. The has_key() method facilitates you to check whether the given key exists or not.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.188.238