[英]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 接受所需的鍵org
和name
,這樣每個輸入字典就可以解壓( **
)到各自的鍵上:
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.