问题描述
因此,提到,如果项缺失,值返回的 default_factory
插入到键的字典中,并返回。这很大一部分时间,但在这种情况下,我实际想要的是返回的值,但不插入defaultdict。
我想我可能的子类defaultdict和覆盖...我猜 __缺少__
?不确定。
您可以子类化 dict
并实现 __ missing __
:
class missingdict(dict):
def __missing __(self,key):
返回'默认'#note,does * not * set self [key]
演示:
>>>> d = missingdict()
>>>> d ['foo']
'default'
>>>> d
{}
您 c> defaultdict ,你会得到工厂处理加副本和pickle支持抛出:
from collections import defaultdict
class missingdict(defaultdict):
def __missing __(self,key):
return self.default_factory()
演示:
> >从集合import defaultdict
>>> class missingdict(defaultdict):
... def __missing __(self,key):
... return self.default_factory()
...
>> ; d = missingdict(list)
>>>> d ['foo']
[]
>>> d
defaultdict(< type'list'>,{})
正如你所看到的, __ repr __
的确是它的名字。
So the defaultdict documentation mentions that, if an item is missing, the value returned by default_factory
"is inserted in the dictionary for the key, and returned." That's great most of the time, but what I actually want in this case is for the value to be returned but not inserted into the defaultdict.
I figured I could probably subclass defaultdict and override... I guess __missing__
? Not sure. What's the best way to go about this?
Thanks in advance.
You can subclass dict
and implement __missing__
:
class missingdict(dict):
def __missing__(self, key):
return 'default' # note, does *not* set self[key]
Demo:
>>> d = missingdict()
>>> d['foo']
'default'
>>> d
{}
You could subclass defaultdict
too, you'd get the factory handling plus copy and pickle support thrown in:
from collections import defaultdict
class missingdict(defaultdict):
def __missing__(self, key):
return self.default_factory()
Demo:
>>> from collections import defaultdict
>>> class missingdict(defaultdict):
... def __missing__(self, key):
... return self.default_factory()
...
>>> d = missingdict(list)
>>> d['foo']
[]
>>> d
defaultdict(<type 'list'>, {})
but, as you can see, the __repr__
does lie about its name.
这篇关于Python defaultdict不插入缺失值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!