Remove a Key Safely

Easy ⏱ 8 min 85% acceptance ★★★★★ 4.7
Write a function remove_key(d, key) that removes key from dict d in place and returns its removed value. If key is not present, return None and leave d unchanged (do not raise an error).

Examples

Example 1
Input
d = {'x': 1, 'y': 2}; remove_key(d, 'x')
Output
1
Explanation

d becomes {'y': 2}, and the removed value 1 is returned.

Example 2
Input
remove_key({'x': 1}, 'z')
Output
None
Explanation

z was never a key, nothing changes.

Constraints

  • Mutate the dict passed in; do not build a new one.

Topics

Dictionariespop()

Companies

MetaCisco

Hints

Hint 1

`d.pop(key, None)` removes and returns the value, or the default if missing.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.