Let us say, we have a Dictionary that contains,
As 'Key' and 'Value' pair.
Now, if you want to remove the entries from a 'Dictionary', 'pop( )', 'popitem( )', 'clear( )' Function and 'del' keyword can be used.
Let us look at the 'pop( )' Function first.
The 'pop( )' Function can be used to remove an item from the Dictionary.
Let us say, we want to remove the entry where the 'Key' is '5' and 'Value' is 'Is a Number'.
x = { 5 : "Is a Number", "John": "Is a Name", "Python": "Is a Language" } x.pop(5) print(x)
So, in the above code we have created a 'Dictionary' using braces '{ }' and 'Key' and 'Value' pairs.
x = { 5 : "Is a Number", "John": "Is a Name", "Python": "Is a Language" }
And initialised to the variable 'x'.
Now, we are supposed to delete the value of the 'Key', '5'.
So, we have used the below way to update it.
And the entry for the 'Key' '5' is deleted for the 'Dictionary'.
And we get the below output,
The 'popitem( )' Function is used to remove the last inserted element from the Dictionary.
x = { 5 : "Is a Number", "John": "Is a Name", "Python": "Is a Language" } x.popitem() print(x)
So, in the above code we have created a 'Dictionary' using braces '{ }' and 'Key' and 'Value' pairs.
x = { 5 : "Is a Number", "John": "Is a Name", "Python": "Is a Language" }
And initialised to the variable 'x'.
Now, we are supposed to delete the last inserted element. And the last inserted element is,
So, we have used the 'popitem( )' to delete it.
And the last entry is deleted for the 'Dictionary'.
And we get the below output,
The 'clear( )' Function can be used to remove all the elements from the Dictionary.
x = { 5 : "Is a Number", "John": "Is a Name", "Python": "Is a Language" } x.clear() print(x)
So, in the above code we have created a 'Dictionary' using braces '{ }' and 'Key' and 'Value' pairs.
x = { 5 : "Is a Number", "John": "Is a Name", "Python": "Is a Language" }
And initialised to the variable 'x'.
And we have used the 'clear( )' method to remove all the elements from the 'Dictionary'.
And the print statement, prints an empty 'Dictionary'.
We have seen, the 'clear( )' Function can be used to remove all the elements from the Dictionary.
Now, let us see, how can we delete a Dictionary completely.
The 'del' keyword is used to remove the Dictionary completely.
x = { 5 : "Is a Number", "John": "Is a Name", "Python": "Is a Language" } del x print(x)
So, we have used the 'del' keyword to delete the Dictionary completely.
And when we try printing the Dictionary,
It ends up with an error.
As the Dictionary 'x' no longer exist.