Python: Remove a key from a dictionary
12. Remove a Key from a Dictionary
Write a Python program to remove a key from a dictionary.
Visual Presentation:

Sample Solution:
Python Code:
# Create a dictionary 'myDict' with key-value pairs.
myDict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# Print the original dictionary 'myDict'.
print(myDict)
# Check if the key 'a' exists in the 'myDict' dictionary.
if 'a' in myDict:
# If 'a' is in the dictionary, delete the key-value pair with the key 'a'.
del myDict['a']
# Print the updated dictionary 'myDict' after deleting the key 'a' (if it existed).
print(myDict)
Sample Output:
{'a': 1, 'b': 2, 'c': 3, 'd': 4} {'b': 2, 'c': 3, 'd': 4}
For more Practice: Solve these Related Problems:
- Write a Python program to remove a specified key from a dictionary using the del statement.
- Write a Python program to remove a key from a dictionary using the pop() method and return its value.
- Write a Python program to implement a function that deletes a key from a dictionary and handles the case when the key does not exist.
- Write a Python program to remove multiple keys from a dictionary by iterating over a list of keys to delete.
Python Code Editor:
Previous: Write a Python program to multiply all the items in a dictionary.
Next: Write a Python program to map two lists into a dictionary.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.