w3resource

Python: Remove a key from a dictionary


Write a Python program to remove a key from a dictionary.

Visual Presentation:

Python Dictionary: Remove a key from a dictionary.

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}

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.



Follow us on Facebook and Twitter for latest update.