Computer Science

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

Python Dictionaries

1 Like

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().

Answered By

2 Likes


Related Questions