Search code examples
pythonpython-2.7dictionarydefaultdict

Accessing key in factory of defaultdict


I am trying to do something similar to this:

from   collections import defaultdict
import hashlib

def factory():
    key = 'aaa'
    return { 'key-md5' : hashlib.md5('%s' % (key)).hexdigest() }

a = defaultdict(factory)
print a['aaa']

(actually, the reason why I need access to the key in the factory is not to compute an md5, but for other reasons; this is just an example)

As you can see, in the factory I have no access to the key: I am just forcing it, which makes no sense whatsoever.

Is it possible to use defaultdict in a way that I can access the key in the factory?


Solution

  • __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}