Deleting a few list items inside of dictionary

和自甴很熟 提交于 2019-12-02 16:21:25

问题


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?


回答1:


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.




回答2:


You can use del() or you can re-create the list by filtering it:

>>> phone = {"first":100,"second":200,"third":[10,12,5,38],"fourth":400}
>>> phone['third'] = [x for x in phone['third'] if x not in (12,5)]
>>> phone
{'second': 200, 'fourth': 400, 'third': [10, 38], 'first': 100}



回答3:


Access values of the phone dictionary, Remove items of the List .

other answer - try get the item (key, value) containing data you want to change. remove it from dictionary. modify values (list) of this item. and then add it to dictionary




回答4:


You can treat phone["third"] as a list since that is what it evaluates to. For instance, if you know the indexes of the items you want to remove you can do:

phone["third"][1:3]=[]

or

del phone["third"][1:3]



回答5:


http://docs.python.org/2/tutorial/datastructures.html#the-del-statement del is a way to delete by index not value, however you can search the index first if you want. Better to use remove if you want to delete by value.

To delete the element at index 1 and 2

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


来源:https://stackoverflow.com/questions/16376471/deleting-a-few-list-items-inside-of-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!