CBSE Class 11 Computer Science Question 25 of 112

Dictionaries — Question 5

Back to all questions
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 ?

  1. fromkeys( )
  2. update( )
  3. setdefault( )
  4. all of these
Answer

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.