【问题标题】:Python How to pass specific key from list of Dictionary to Map functionPython 如何将字典列表中的特定键传递给 Map 函数
【发布时间】:2023-01-27 19:51:50
【问题描述】:

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

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)

由于数据包含不同的键,我需要将 org 映射到 org_name ,但我不确定如何使用 map 函数传递

【问题讨论】:

  • 最简单的方法是编写一个包装函数,它接受一个字典并调用process_data。然后可以在 map 调用中使用包装器。

标签: python multithreading map-function


【解决方案1】:

当你使用数据作为可迭代的地图()将会发生的是列表中的每个元素都将传递给 process_data。该函数仅接收一个参数。

所以...

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)

...可能有助于澄清

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多