CBSE Class 11 Computer Science Question 28 of 112

Dictionaries — Question 8

Back to all questions
8
Question

Question 8

Which of the following can be used to delete item(s) from a dictionary?

  1. del statement
  2. pop( )
  3. popitem( )
  4. all of these
Answer

all of these

Reason

  1. del keyword is used to delete an item with the specified key name.
    For example:
d =	{'list': 'mutable', 'tuple': 'immutable', 'dictionary': 'mutable'} 
del dict["tuple"]
print(d)
Output
{'list': 'mutable', 'dictionary': 'mutable'} 

del keyword deletes the key "tuple" and it's corresponding value.

  1. pop() method removes the item with the specified key name: For example:
d =	{'list': 'mutable', 'tuple': 'immutable', 'dictionary': 'mutable'} 
d.pop("tuple")
print(d)
Output
{'list': 'mutable', 'dictionary': 'mutable'} 

The key named "tuple" is popped out. Hence dictionary d has only two key-value pairs.

  1. popitem() method removes the last inserted item of dictionary.
    For example:
d =	{'list': 'mutable', 'tuple': 'immutable', 'dictionary': 'mutable'} 
d.popitem()
print(d)
Output
{'list': 'mutable', 'tuple': 'immutable'} 

Here, the last element of d was 'dictionary': 'mutable' which gets removed by function popitem().