简体   繁体   English

使用collections.defaultdict中的密钥

[英]Using the key in collections.defaultdict

collections.defaultdict is great. collections.defaultdict很棒。 Especially in conjunction with lambda : 特别是与lambda一起使用:

>>> import collections
>>> a = collections.defaultdict(lambda : [None,None])
>>> a['foo']
[None, None]

Is there a way to use the key given (eg 'foo' ) in the lambda? 有没有办法在lambda中使用给定的键(例如'foo' )? For example (doesn't work): 例如(不起作用):

>>> a = collections.defaultdict(lambda : [None]*key)
>>> a[1]
[None]
>>> a[2]
[None, None]
>>> a
defaultdict(<function <lambda> at 0x02984170>, {1: [None], 2: [None, None]})

You probably want __missing__ which is called on dict whenever you try to access an item not present in the dict; 您可能想要__missing__ ,只要您尝试访问dict中不存在的项目,就会在dict上调用它。 the vanilla __missing__ raises an exception, but you could do whatever you like in a subclass: vanilla __missing__引发异常,但你可以在子类中做任何你喜欢的事情:

class A(dict):
    def __missing__(self, key):
        value = self[key] = [None] * key
        return value

Combining the answers from SingleNegationElimination and rplnt , and the defaultdict documentation , I used the following solution. 结合SingleNegationEliminationrplnt以及defaultdict文档的答案,我使用了以下解决方案。

import collections
class KeyBasedDefaultDict(collections.defaultdict):
    def __missing__(self, key):
        if self.default_factory is None:
            raise KeyError(key)
        self[key] = self.default_factory(key)
        return self[key]

The body of the method could possibly just be return self.default_factory(key) , but the extra code makes sure to replicate all defaultdict behaviour. 该方法的主体可能只是return self.default_factory(key) ,但额外的代码确保复制所有defaultdict行为。

Usage as described in question: 使用情况如下所述:

d = KeyBasedDefaultDict(lambda key: [None] * key)
d[1]
> [None]
d[2]
> [None, None]

This will work as requested, although it's probably not the best solution (you need to initialize it with default call and then not use it). 这将按要求工作,虽然它可能不是最好的解决方案(您需要使用默认调用初始化它,然后不使用它)。 It could probably be fixed with overriding some other method(s). 它可能可以通过覆盖其他一些方法来修复。

class NoneDict(collections.defaultdict):
    def __setitem__(self, key, value):
        super(NoneDict, self).__setitem__(key, key*[None])

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

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