Accessing key in factory of defaultdict

后端 未结 2 767
醉话见心
醉话见心 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:29

    __missing__ of defaultdict does not pass key to factory function.

    If default_factory is not None, it is called without arguments to provide a default value for the given key, this value is inserted in the dictionary for the key, and returned.

    Make your own dictionary class with custom __missing__ method.

    >>> class MyDict(dict):
    ...     def __init__(self, factory):
    ...         self.factory = factory
    ...     def __missing__(self, key):
    ...         self[key] = self.factory(key)
    ...         return self[key]
    ... 
    >>> d = MyDict(lambda x: -x)
    >>> d[1]
    -1
    >>> d
    {1: -1}
    

提交回复
热议问题