8
Question Question 8
Which of the following can be used to delete item(s) from a dictionary?
- del statement
- pop( )
- popitem( )
- all of these
all of these
Reason —
- 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.
- 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.
- 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().