开发者

Best method to delete an item from a dict [closed]

Closed. This question is opinion-based. It is not currently accepting answers.

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed 2 years ago.

Improve this question

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

d = 开发者_如何学Python{"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.


  • 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]


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


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜