Accessing key in factory of defaultdict
我想尝试做类似的事情:
1 2 3 4 5 6 7 8 9 | from collections import defaultdict import hashlib def factory(): key = 'aaa' return { 'key-md5' : hashlib.md5('%s' % (key)).hexdigest() } a = defaultdict(factory) print a['aaa'] |
(实际上,我需要访问工厂中的密钥的原因不是计算
正如你所看到的,在工厂里我无法访问密钥:我只是强迫它,这没有任何意义。
是否可以以我可以在工厂中访问密钥的方式使用
If
default_factory is notNone , 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.
使用自定义
1 2 3 4 5 6 7 8 9 10 11 12 | >>> 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} |
不幸的是,不是直接的,因为defaultdict指定必须在没有参数的情况下调用default_factory:
http://docs.python.org/2/library/collections.html#collections.defaultdict
但是可以使用defaultdict作为具有所需行为的基类:
1 2 3 4 5 6 7 | 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) |
这对我有用:
1 2 3 4 5 6 7 | >>> a = CustomDefaultdict(factory) >>> a defaultdict(<function factory at 0x7f0a70da11b8>, {}) >>> print a['aaa'] {'key-md5': '47bce5c74f589f4867dbd57e9ca9f808'} >>> print a['bbb'] {'key-md5': '08f8e0260c64418510cefb2b06eee5cd'} |