Python Practice › Dictionary Programs › Program 24
Remove a key
Write a Python program to remove a key from a dictionary.
Input
{"a": 2, "b": 4, "c": 5}, remove "c"Output
5 {'a': 2, 'b': 4}
not foundApproach
pop(key, default)removes safely;delraises KeyError for a missing key.
Solution
d = {"a": 2, "b": 4, "c": 5}removed = d.pop("c")print(removed, d)print(d.pop("zzz", "not found"))Output
5 {'a': 2, 'b': 4}
not foundLearn the concept
New to this topic? Read the lesson, then come back.