Computer Science
Answer
Yes, key:value pairs can be removed from a dictionary. The different methods to remove key:value pairs are given below:
1. By using del command:
It is used to delete an item with the specified key name. The syntax for doing so is as given below:
del <dictionary>[<key>]
For example:
dict = {'list': 'mutable', 'tuple': 'immutable', 'dictionary': 'mutable'}
del dict["tuple"]
print(dict)
Output
{'list': 'mutable', 'dictionary': 'mutable'}
2. By using pop() method:
This method removes and returns the dicitionary element associated to the passed key. It is used as per the syntax:
<dict>.pop(key, <value>)
For example:
dict = {'list': 'mutable', 'tuple': 'immutable', 'dictionary': 'mutable'}
dict.pop("tuple")
print(dict)
Output
{'list': 'mutable', 'dictionary': 'mutable'}
3. popitem() method:
This method removes and returns the last inserted item in the dictionary. It is used as per the syntax:
<dict>.popitem()
For example:
dict = {'list': 'mutable', 'tuple': 'immutable', 'dictionary': 'mutable'}
dict.popitem()
print(dict)
Output
{'list': 'mutable', 'tuple': 'immutable'}
Here, the last element of dict was 'dictionary': 'mutable' which gets removed by function popitem().