Search code examples
pythonlistdictionarydel

Deleting a few list items inside of dictionary


Deleting a few list items inside of dictionary

Hi, I have a dictionary:

phone = {"first":100,"second":200,"third":[10,12,5,38],"fourth":400}

Let' say I want to remove the 12 and 5 from from "phone" dictionary. Is there a way to do that using a "del" function?

I know how to do this, using a .remove()

phone["third"].remove(12)
phone["third"].remove(5)

but I was wondering if it is possible to do it using the del()? Thank you.

EDIT: For all those replies concentrating on "del uses index, remove uses the exact value", I am redefining my question:

I want to delete the indexes 1 and 2 in the list representing the third key-value item in "phone" dictionary. How can I do that?


Solution

  • You have to do this by index rather than value:

    >>> phone = {"first":100,"second":200,"third":[10,12,5,38],"fourth":400}
    >>> del(phone["third"][1:3])
    >>> phone
    {'second': 200, 'fourth': 400, 'third': [10, 38], 'first': 100}
    

    This deletes elements in position 1 and 2 in the list.