Remove Item from Dictionary by Key in Python
Below are some of the ways by which we can remove the item from a dictionary by key in Python:
- Using del Keyword
- Using pop() Method
- Using popitem() Method
Remove Item from Dictionary by Key Using del keyword
In this example, a dictionary named dict1
is created with key-value pairs representing a person’s information. The code then deletes the ‘Job’ key and its corresponding value from the dictionary, demonstrating the use of the del
keyword to remove an item.
Python3
dict1 = { 'Name' : 'John' , 'Age' : 25 , 'Job' : 'Developer' } print ( "Original Dictionary: " , dict1) del dict1[ 'Job' ] print ( "Dictionary after deleting an item: " , dict1) |
Original Dictionary: {'Name': 'John', 'Age': 25, 'Job': 'Developer'} Dictionary after deleting an item: {'Name': 'John', 'Age': 25}
Remove Item from Dictionary by Key Using pop() Method
In this example, a dictionary named dict2
is created with key-value pairs. The code uses the pop
method to remove the item with the key ‘Age’ from the dictionary, storing the removed value in the variable removed_value
. The updated dictionary and the popped value are then displayed.
Python3
dict2 = { 'Name' : 'John' , 'Age' : 25 , 'Job' : 'Developer' } print ( "Original Dictionary: " , dict2) removed_value = dict2.pop( 'Age' ) print ( "Dictionary after popping an item: " , dict2) print ( "Popped value: " , removed_value) |
Original Dictionary: {'Name': 'John', 'Age': 25, 'Job': 'Developer'} Dictionary after popping an item: {'Name': 'John', 'Job': 'Developer'} Popped value: 25
Remove Item from Dictionary by Key Using popitem() Method
In this example, the dictionary student
contains information about a student. The popitem()
method is used to remove and return the last key-value pair from the dictionary. The updated dictionary without the popped item is printed, along with the removed key-value pair stored in the variable pair
.
Python3
student = { 'name' : 'John' , 'age' : 16 , 'grade' : 10 } print ( "Original Dictionary: " , student) pair = student.popitem() print ( "Dictionary After Removal by Key:" , student) |
Original Dictionary: {'name': 'John', 'age': 16, 'grade': 10} Dictionary After Removal by Key: {'name': 'John', 'age': 16}
Python Remove Item from Dictionary by Key
A dictionary in Python is a mutable and dynamic data type that provides a flexible way to access and manipulate data. As distinct from a list or a tuple, where elements are accessed via indices, a dictionary leverages a unique key representing each item. In this article, we will see how to remove items from the dictionary by key in Python.