Accessing key in factory of defaultdict

后端 未结 2 768
醉话见心
醉话见心 2021-02-19 23:17

I am trying to do something similar to this:

from   collections import defaultdict
import hashlib

def factory():
    key = \'aaa\'
    return { \'key-md5\' : ha         


        
2条回答
  •  情书的邮戳
    2021-02-19 23:34

    Unfortunately not directly, as defaultdict specifies that default_factory must be called with no arguments:

    http://docs.python.org/2/library/collections.html#collections.defaultdict

    But it is possible to use defaultdict as a base class that has the behavior you want:

    class CustomDefaultdict(defaultdict):
        def __missing__(self, key):
            if self.default_factory:
                dict.__setitem__(self, key, self.default_factory(key))
                return self[key]
            else:
                defaultdict.__missing__(self, key)
    

    This works for me:

    >>> a = CustomDefaultdict(factory)
    >>> a
    defaultdict(, {})
    >>> print a['aaa']
    {'key-md5': '47bce5c74f589f4867dbd57e9ca9f808'}
    >>> print a['bbb']
    {'key-md5': '08f8e0260c64418510cefb2b06eee5cd'}
    

提交回复
热议问题