Removing Dictionary Key

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

Example 1:

Input: {"a": 5, "b": 3, "c": 2}, "b" 
Output: {"a": 5, "c": 2}

Example 2:

Input: {"x": 7, "y": 2, "z": 1}, "z" 
Output: {"x": 7, "y": 2}

Use Python’s built-in dict.pop() method.

def remove_key(d, key):
    d.pop(key, None)
    return d

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!