How to remove an item from a Python Dictionary?

Specifically, how can I create a new dictionary with the item removed, without modifying the original dictionary?

Been working with Python for years, and I find that the del statement is the most straightforward way to remove an item from a dictionary. But if you want to keep your original dictionary intact, you can create a copy before removing the key."

def removekey(d, key):
    r = dict(d)  # Create a shallow copy
    del r[key]  # Remove the key
    return r

This ensures the original dictionary remains untouched, and the returned dictionary reflects the updated state. If you need a deep copy, check out the copy module.

That works well, but if you’re looking for a more Pythonic and functional approach to remove an item from a dictionary without using del, dictionary comprehension is a great alternative.

def removekey(d, key):
    return {k: v for k, v in d.items() if k != key}

This creates a new dictionary containing all elements except the specified key. No need for del, and it’s super readable!

Both of those methods are solid, but if you want a built-in function that naturally handles this, pop is a great option. The advantage? You can also specify a default value to avoid errors if the key doesn’t exist.

def removekey(d, key):
    r = dict(d)  # Create a copy
    r.pop(key, None)  # Remove the key safely
    return r

Using pop(key, None) ensures that the function won’t throw an error if the key isn’t found. This is a safe way to remove an item from a dictionary without affecting the original.