Write a Python program to Delete a list of keys from a dictionary


The program demonstrates how to remove key-value pairs from a dictionary in Python. The dictionary student contains information about a student, including their name, roll number, marks, age, gender, and city. The list keys contains the keys that we want to remove from the student dictionary: "Gender" and "City".

The program then uses a for loop to iterate over the elements in the keys list. For each element in the keys list, the pop method is used to remove the key-value pair with the corresponding key from the student dictionary.

Source Code

"""
student = {
	"Name": "Tara",
	"RollNo":130046, 
	"Mark": 458, 
	"Age":16,
	"Gender":"Female",
	"City": "Chennai"
}
print("Before Delete :",student)
# Keys to remove From a Dict
keys = ["City","Gender"]
 
student = {k: student[k] for k in student.keys() - keys}
print("After Delete :",student)
"""
 
student = {
	"Name": "Tara",
	"RollNo":130046, 
	"Mark": 458, 
	"Age":16,
	"Gender":"Female",
	"City": "Chennai"
}
print("Before Delete :",student)
# Keys to remove From a Dict
keys = ["Gender", "City"]
 
for k in keys:
    student.pop(k)
print("After Delete :",student)
 

Output

Before Delete : {'Name': 'Tara', 'RollNo': 130046, 'Mark': 458, 'Age': 16, 'Gender': 'Female', 'City': 'Chennai'}
After Delete : {'Name': 'Tara', 'RollNo': 130046, 'Mark': 458, 'Age': 16}