访问工厂的关键字defaultdict [英] Accessing key in factory of defaultdict

查看:126
本文介绍了访问工厂的关键字defaultdict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试类似的操作:

 从集合导入defaultdict 
import hashlib

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

a = defaultdict(factory)
打印a ['aaa']

(实际上,为什么我需要访问工厂的密钥的原因不是计算一个 md5 ,而是出于其他原因,这只是一个例子) p>

正如你所看到的,在工厂我无法访问密钥:我只是强迫它,这没有任何意义。



可以使用 defaultdict ,以便我可以在工厂中访问密钥?

解决方案

__缺少 defaultdict 的__ 不通过到工厂功能。


如果 default_factory 不是,它被称为无参数
提供给定键的默认值,此值插入
键入的字典,并返回。


使用自定义的 __缺少__ 方法。

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


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?

解决方案

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

这篇关于访问工厂的关键字defaultdict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆