May 2017
Intermediate to advanced
280 pages
6h 2m
English
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 ...
Read now
Unlock full access