Best method to delete an item from a dict

Python

Python Problem Overview


In Python there are at least two methods to delete an item from a dict using a key.

d = {"keyA": 123, "keyB": 456, "keyC": 789}

#remove via pop
d.pop("keyA")

#remove via del
del d["keyB"]

Both methods would remove the item from the dict.

I wonder what the difference between these methods is and in what kinds of situations I should use one or the other.

Python Solutions


Solution 1 - Python

  • Use d.pop if you want to capture the removed item, like in item = d.pop("keyA").

  • Use del if you want to delete an item from a dictionary.

  • If you want to delete, suppressing an error if the key isn't in the dictionary: if thekey in thedict: del thedict[thekey]

Solution 2 - Python

pop returns the value of deleted key.
Basically, d.pop(key) evaluates as x = d[key]; del d[key]; return x.

  • Use pop when you need to know the value of deleted key
  • Use del otherwise

Solution 3 - Python

Most of the time the most useful one actually is:

d.pop("keyC", None)

which removes the key from the dict, but does not raise a KeyError if it didn't exist.

The expression also conveniently returns the value under the key, or None if there wasn't one.

Solution 4 - Python

I guess it comes down to if you need the removed item returned or not. pop returns the item removed, del does not.

Solution 5 - Python

Using a very simple timer I tested the efficiency of these functions: > def del_er(nums,adict): for n in nums: del adict[n] > def pop_er(nums,adict): for n in nums: adict.pop(n) On my system, using 100,000 item dict and 75,000 randomly selected indices, del_er ran in about .330 seconds, pop_er ran in about .412 seconds.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncircusView Question on Stackoverflow
Solution 1 - PythonWang DingweiView Answer on Stackoverflow
Solution 2 - PythonFeniksoView Answer on Stackoverflow
Solution 3 - PythonruoholaView Answer on Stackoverflow
Solution 4 - PythonTobias EinarssonView Answer on Stackoverflow
Solution 5 - PythongriswolfView Answer on Stackoverflow