Computer Science
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
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
3 Likes
Related Questions
Dictionaries are …………. data types of Python.
- mutable
- immutable
- simple
- all of these
Which of the following functions will return the key, value pairs of a dictionary ?
- keys( )
- values( )
- items( )
- all of these
Which of the following will create a dictionary with given keys and a common value ?
- fromkeys( )
- update( )
- setdefault( )
- all of these
Which value is assigned to keys, if no value is specified with the fromkeys() method ?
- 0
- 1
- None
- any of these