使用kwargs作为字典中的键
问题描述:
我有一种方法可以检索kwargs和未来。 我想将kwargs的字典保存到将来,以便以后用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创建了一个元组!
答
这种情况的典型解决方法是使用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
这意味着你有** **字典在一个'kwargs'的**值**。 –
我明白了。所以我需要每个值都包含一个元组? – Dejell
你确实可以将每个字典转换为一个元组的等价物。请注意,您将不得不以递归方式**这样做,因为这些字典也可以包含字典等。 –