我正在运行一个函数,该函数旨在通过具有多个输入的starmap返回字典变量。但是,当我打印由多处理产生的最终输出时,我得到的是一个列表类型变量。为什么会发生这种情况,是否有解决方法?谢谢。
的例子:
from multiprocessing import Pool
def return_dict(keys, values):
dict =dict(zip(keys, values))
print(type(dict))
return dict
with Pool(3) as p:
output = p.starmap(return_dict, [(['name', 'age', 'nationality'], ['Bob', 17, 'Korean']),
(['price', 'fruit', 'drink'], [20, 'banana', 'juice']),
(['color1', 'color2', 'color3'], ['red', 'blue', 'green']))
print(type(output))
输出:
<class 'dict'>
<class 'dict'>
<class 'dict'>
<class 'list'>
您可以通过以下方式获得所需的结果。此外,我的建议是在一个过程中进行如此简单的操作,而不是使用Pool
from multiprocessing import Pool
def return_dict(keys, values):
# use dictionary comprehension to create dictionary
_dict = {keys[i]: values[i] for i in range(len(keys))}
print(type(_dict))
return _dict
if __name__ == '__main__':
data = [
(
['name', 'age', 'nationality'],
['Bob', 17, 'Korean'],
),
(
['price', 'fruit', 'drink'],
[20, 'banana', 'juice'],
),
(
['color1', 'color2', 'color3'],
['red', 'blue', 'green'],
)
]
with Pool(3) as p:
output = p.starmap(return_dict, data)
for j in output:
print(j)