从Python字典中删除项目的最佳方式? [英] Best way to remove an item from a Python dictionary?

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

问题描述

当项目的键未知时,从字典中删除项目的最佳方式是什么?这是一个简单的方法:

What is the best way to remove an item from a dictionary when the item's key is unknown? Here's a simple approach:

for key, item in some_dict.items():
    if item is item_to_remove:
        del some_dict[key]

有更好的方法吗?

推荐答案

请注意,您正在测试对于对象身份(只返回 True 如果两个操作数都由内存中的同一个对象表示 - 这并不总是两个对象的情况与 == 相比较)。如果您有意这样做,那么您可以将代码重写为

Be aware that you're currently testing for object identity (is only returns True if both operands are represented by the same object in memory - this is not always the case with two object that compare equal with ==). If you are doing this on purpose, then you could rewrite your code as

some_dict = {key: value for key, value in some_dict.items() 
             if value is not value_to_remove}

但这可能不会做什么你想要:

But this may not do what you want:

>>> some_dict = {1: "Hello", 2: "Goodbye", 3: "You say yes", 4: "I say no"}
>>> value_to_remove = "You say yes"
>>> some_dict = {key: value for key, value in some_dict.items() if value is not value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 3: 'You say yes', 4: 'I say no'}
>>> some_dict = {key: value for key, value in some_dict.items() if value != value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 4: 'I say no'}

所以你可能想要!= 而不是不是

So you probably want != instead of is not.

这篇关于从Python字典中删除项目的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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