为了搭载sqreept的答案,以下是该类的子类,dict
其行为符合预期:
class DictNoNone(dict):
def __setitem__(self, key, value):
if key in self or value is not None:
dict.__setitem__(self, key, value)
d = DictNoNone()
d["foo"] = None
assert "foo" not in d
这将允许将现有键的值更改为None
,但是分配None
给不存在的键是无操作的。如果你想设置的项目None
,以除去从如果它已经存在的字典,你可以这样做:
def __setitem__(self, key, value):
if value is None:
if key in self:
del self[key]
else:
dict.__setitem__(self, key, value)
如果在构造过程中传递它们,则None
可以获取的值。如果要避免这种情况,请添加一种__init__
方法将其过滤掉:
def __init__(self, iterable=(), **kwargs):
for k, v in iterable:
if v is not None: self[k] = v
for k, v in kwargs.iteritems():
if v is not None: self[k] = v
您也可以通过编写使其通用,以便在创建字典时传递所需的条件:
class DictConditional(dict):
def __init__(self, cond=lambda x: x is not None):
self.cond = cond
def __setitem__(self, key, value):
if key in self or self.cond(value):
dict.__setitem__(self, key, value)
d = DictConditional(lambda x: x != 0)
d["foo"] = 0
assert "foo" not in d
'orange': orange if orange else default
语法。