Computer Science
Can you remove key:value pairs from a dictionary and if so, how?
Python Dictionaries
CBSE
2 Likes
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().
Answered By
1 Like
Related Questions
What do you understand by ordered collection and unordered collection ? Give examples.
Can you change an element of a sequence or collection? What if a collection is a dictionary? What if a sequence is a string?
Which of the following types qualify to be the keys of a dictionary?
- String
- tuple
- Integer
- float
- list
- dictionary
How do you add key:value pairs to an existing dictionary?