简体   繁体   English

不插入缺失值的 Python defaultdict

[英]Python defaultdict that does not insert missing values

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."因此defaultdict 文档提到,如果缺少某个项目,则default_factory返回的值“将插入到键的字典中,并返回”。 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.大多数时候这很好,但在这种情况下我真正想要的是返回值但插入到 defaultdict 中。

I figured I could probably subclass defaultdict and override... I guess __missing__ ?我想我可以子类 defaultdict 并覆盖...我猜__missing__ Not sure.不确定。 What's the best way to go about this?解决这个问题的最佳方法是什么?

Thanks in advance.提前致谢。

You can subclass dict and implement __missing__ :您可以__missing__ dict并实现__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:也可以将defaultdict子类化,您将获得工厂处理加上复制和泡菜支持:

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.但是,正如您所看到的, __repr__确实对其名称__repr__谎。

It's even simpler than subclassing.它甚至比子类化更简单。 While dict[key] adds the key, dict.get(key, default=None) will NOT add the key to the dictionary:虽然dict[key]添加键,但dict.get(key, default=None)不会将键添加到字典中:

import collections

d = collections.defaultdict(int)

assert d['test1'] == 0

print(d)
# defaultdict(<class 'int'>, {'test1': 0})

assert d.get('test2', 0) == 0
# for a more generic version, use `d.default_factory()` instead of 0

print(d)
# defaultdict(<class 'int'>, {'test1': 0})
# => did NOT insert a key for 'test2' =)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM