How to delete an entry from a dictionary in Python?

In python the command "del m[k]" to delete an item in a dictionary seems like an odd grammatical construction doesn't it? Should it not have been "m[k].del" or something like that? What am I missing?

  • Answer:

    No, it's not strange. Why would m[k] be in charge of deleting itself? Not to mention that "del m[k]" doesn't actually delete that object. It deletes that reference called "m[k]": >>> s="foo" >>> l=[1,2,s] >>> del l[2] >>> l [1, 2] >>> s 'foo' Having del be a method of the object would imply that you are deleting the object, not the reference, and that all references to it would be deleted, which is a surefire way to make something else misbehave.

Roberto Alsina at Quora Visit the source

Was this solution helpful to you?

Other answers

As Roberto Alsina mentioned, "m[k].del()" would not make any sense, as that would do something on the value in the dictionary, as opposed to the dictionary itself. A better question would be why it is not something like "m.del(k)", i.e. a method on the dictionary. Indeed, in most languages, that's how it would be done. And dictionaries do have a method "pop", i.e. "m.pop(k)" that does the same thing (plus returning the item removed). If you look more into it, in the Python language, "del m[k]" is equivalent to "m.__delitem__(k)", so under the covers, it does call a method on the dictionary.

Xuan Luo

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.