Computer Science
Which of the following can be used to delete item(s) from a dictionary?
- del statement
- pop( )
- popitem( )
- all of these
Python Dictionaries
1 Like
Answer
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().
Answered By
3 Likes
Related Questions
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
Which of the following will raise an error if the given key is not found in the dictionary ?
- del statement
- pop( )
- popitem()
- all of these
Which of the following will raise an error if the given dictionary is empty ?
- del statement
- pop( )
- popitem( )
- all of these