从Python中的dict中删除值 [英] Removing values from dict in python

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

问题描述

此代码:

a = {'sd':{},'sdd':'','sadfas':None,'sadfa':'dsf'}
a = dict((k, v) for k, v in a.iteritems() if v is not '' or v != {} or v is not None)
print a

打印:

{'sdd': '', 'sadfas': None, 'sadfa': 'dsf', 'sd': {}}

但是,它并不能从dict中删除我需要删除的所有类型的值.为什么会这样?

However, it does not remove all the type of values from dict which i need to remove. Why is that ?

如果我这样做,这些值将被删除:

These values are removed if i do:

a = {'sd':{},'sdd':'','sadfas':None,'sadfa':'dsf'}

a=dict((k, v) for k, v in a.iteritems() if v is not '')
a=dict((k, v) for k, v in a.iteritems() if v is not None)
a=dict((k, v) for k, v in a.iteritems() if v)

print a

此打印:

{'sadfa': 'dsf'}

这是我们想要的,但是我必须遍历字典3次才能实现.您能建议一种更优化的方法吗?

which is what we want, but i have to iterate over dictionary 3 times in order to achieve. Can you suggest a more optimised way.

推荐答案

这里有两个问题:

  1. v不是''应该是 v!=''.您应该始终使用 == != 来比较两个值,因为 is not 用于比较两个对象的身份.

  1. v is not '' should be v != ''. You should always use == and != to compare two values because is and is not are for comparing the identities of two objects.

您需要使用而不是 or .否则,这种情况:

You need to use and instead of or. Otherwise, this condition:

v != '' or v != {} or v is not None

将始终为 True ,因为 v 始终不等于''或不等于 {} .

will always be True because v will always be either not equal to '' or not equal to {}.

下面是您的代码的固定版本:

Below is a fixed version of your code:

>>> a = {'sd':{},'sdd':'','sadfas':None,'sadfa':'dsf'}
>>> a = dict((k, v) for k, v in a.iteritems() if v != '' and v != {} and v is not None)
>>> a
{'sadfa': 'dsf'}
>>>


但是,我们可以进一步简化它:


However, we can simplify this further:

>>> a = {'sd':{},'sdd':'','sadfas':None,'sadfa':'dsf'}
>>> a = dict((k, v) for k, v in a.iteritems() if v)
>>> a
{'sadfa': 'dsf'}
>>>

此解决方案之所以有效,是因为'' {} None 均评估为 False .

This solution works because '', {}, and None all evaluate to False.

这篇关于从Python中的dict中删除值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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