5
Question Question 5
Which of the following will add a key to the dictionary only if it does not already exist in the dictionary ?
- fromkeys( )
- update( )
- setdefault( )
- all of these
setdefault()
Reason — setdefault() function is used to return the value of a key (if the key is in dictionary). Else, it inserts a key with the default value to the dictionary.
For example:
d = {"list": "mutable","tuple": "immutable"}
d.setdefault("dictionaries", "mutable")Output
mutable
Since "dictionaries" named key does not exist in dict, therefore setdefault() function inserts it to the dictionary d and returns the value of it.