Remove a key

EasyDictionary Programs · 24 of 94

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

Advertisement
Input
{"a": 2, "b": 4, "c": 5}, remove "c"
Output
5 {'a': 2, 'b': 4}
not found

Approach

  1. pop(key, default) removes safely; del raises KeyError for a missing key.

Solution

Python
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 found
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs