Computer Science

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

Python Dictionaries

2 Likes

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.

Answered By

1 Like


Related Questions