繁体   English   中英

Python 如何将字典列表中的特定键传递给 Map function

[英]Python How to pass specific key from list of Dictionary to Map function

我有以下格式的数据: 我有 function 接受 2 个关键字参数 我无法提供语法或示例,我可以将特定键从字典列表传递到 Map function 以作为多线程运行

import concurrent.futures

data = [
    {
        "name": "abc",
        "org": "pqr"
    },
    {
        "name": "xyz",
        "org": "sdf"
    }
    ]
def process_data(org_name, cu_name):
    print(org_name)
    print(cu_name)

with concurrent.futures.ThreadPoolExecutor() as Executor:
   results = Executor.map(process_data, data)

由于数据包含不同的密钥,我需要 map org 到 org_name,但我不确定如何通过 map function

当您将数据用作map()中的可迭代对象时,将发生的是列表中的每个元素都将传递给 process_data。 那个function只接收一个参数。

所以...

from concurrent.futures import ThreadPoolExecutor as TPE

data = [
    {
        "name": "abc",
        "org": "pqr"
    },
    {
        "name": "xyz",
        "org": "sdf"
    }
]

def process_data(d):
    for k, v in d.items():
        print(f'{k} = {v}')

with TPE() as tpe:
    tpe.map(process_data, data)

...可能有助于澄清

让您的process_data function 接受所需的键orgname ,这样每个输入字典就可以解压( ** )到各自的键上:

def process_data(org, name):
    print(org, name)

with concurrent.futures.ThreadPoolExecutor() as Executor:
   results = Executor.map(lambda kargs: process_data(**kargs), data)

pqr abc
sdf xyz
    import concurrent.futures

data = [
    {
        "name": "abc",
        "org": "pqr"
    },
    {
        "name": "xyz",
        "org": "sdf"
    }
]


def process_data(org_name, cu_name):
    print(f'org = {org_name}')
    print(f'cu ={cu_name}')



with concurrent.futures.ThreadPoolExecutor() as Executor:
    result = Executor.map(lambda d: process_data(org_name=d['name'], cu_name=d['org']), data)

感谢迈克尔,这对我有用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM