首页 > 解决方案 > 多处理星图返回列表而不是字典

问题描述

我正在运行一个函数,该函数旨在通过具有多个输入的星图返回字典变量。但是,当我打印多处理产生的最终输出时,我得到了一个列表类型变量。为什么会发生这种情况,是否有解决方法?谢谢。

例子:

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

标签: pythonmultiprocessing

解决方案


您可以通过以下方式获得所需的结果。另外我的建议是在一个过程中进行如此简单的操作而不是使用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)

推荐阅读