删除字典中的几个列表项 [英] Deleting a few list items inside of dictionary

查看:131
本文介绍了删除字典中的几个列表项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

删除字典内的几个列表项目




我有一个字典:

  phone = {first:100,second:200,third:[10,12,5,38],fourth:400} 
让我们想从手机字典中删除12和5。
有没有办法使用del功能?



我知道如何使用.remove()

 手机[第三]删除(12)
手机[第三]删除(5)

但我想知道是否可以使用del()?
谢谢。



编辑:对于所有那些专注于del使用索引,删除使用确切值的回复,我正在重新定义我的问题: p>

我想删除表示手机字典中第三个键值项的列表中的索引1和2。我该怎么做?

解决方案

你必须通过索引而不是价值来做到这一点:

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

删除列表中位置1和2中的元素。


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?

解决方案

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.

这篇关于删除字典中的几个列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆