Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 794
circus Avatar asked Apr 19 '11 07:04

circus


People also ask

Which method removes all items from the particular dictionary?

The clear() method removes all items from the dictionary.

How do I remove an item from a dictionary Python?

To remove a key from a dictionary in Python, use the pop() method or the “del” keyword. Both methods work the same in that they remove keys from a dictionary. The pop() method accepts a key name as argument whereas “del” accepts a dictionary item after the del keyword.


2 Answers

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

like image 197
Wang Dingwei Avatar answered Sep 23 '22 09:09

Wang Dingwei


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
like image 40
Fenikso Avatar answered Sep 26 '22 09:09

Fenikso