使用kwargs作为字典中的键

时间:2017-04-05 13:16:37

标签: python dictionary

我有一个方法可以检索kwargs和future。 我想将kwargs的字典保存到未来,以便以后用kwargs处理未来的结果。

class ThreadPoolExecutorImproved(object):

def __init__(self, max_workers):
    self._executor = ThreadPoolExecutor(max_workers)
    self._futures = {}

def __enter__(self):
    return self

def __exit__(self, exc_type, exc_val, exc_tb):
    kwargs_to_exception = {}
    for kwargs, future in self._futures.iteritems():
        if future.exception():
            kwargs_to_exception[kwargs] = future.exception

    if kwargs_to_exception:
        raise ThreadPoolException(kwargs_to_exception)

def submit(self, fn, *args, **kwargs):
    future = self._executor.submit(fn, *args, **kwargs)
    key = tuple(kwargs.items())
    self._futures[key] = future
    return future

但是,我在第self.futures[key] = future行上收到错误:

TypeError: unhashable type: 'dict' for python

为什么?我用kwargs创建了一个元组!

1 个答案:

答案 0 :(得分:1)

这种情况的典型解决方法是使用future作为密钥; 你的代码

key = tuple(kwargs.items())
self._futures[key] = future

迁移到

self._futures[future] = tuple(kwargs.items())

当你想要处理self._futures时,你可以迭代这个

for future, kw in self._futures:
    # check kw
    # do your stuff
相关问题