Instagram
youtube
Facebook
Twitter

Python Program to Delete a List of Keys from a Dictionary

A Python Program to Delete a List of Keys from a Dictionary?

Code Explanation:

Original Dictionary:
A dictionary sample_dict is created with keys like name, age, gender, and location.

Keys to Remove:
A list keys_to_remove contains the keys that should be deleted from the dictionary.

Loop and Remove:
A for loop is used to iterate over keys_to_remove.
pop(key, None) is used to remove the key if it exists; None prevents errors if the key is missing.

Print Result:
The updated dictionary is printed, showing only the remaining key-value pairs.

 

Program:

sample_dict = {

    "name": "John",

    "age": 25,

    "gender": "Male",

    "location": "New York"

}

keys_to_remove = ["age", "location"]

for key in keys_to_remove:

    sample_dict.pop(key, None)

print("Updated dictionary:", sample_dict)