当前位置: 动力学知识库 > 问答 > 编程问答 >

Python Threading: How to build a dictionary from the results

问题描述:

I have the following code nested in another function (so this isn't any kind of stand alone file):

train_set_percentages = [0.2,0.5,0.8,1.0]

results = {}

for i in range(len(train_set_percentages)):

kf2_index_percent,kf5_index_percent,loo_index_percent = generate_data_entry(train_set_percentages[i])

results[kf2_index_percent[0]] = kf2_index_percent[1]

results[kf5_index_percent[0]] = kf5_index_percent[1]

results[loo_index_percent[0]] = loo_index_percent[1]

generate_data_entry returns the three tuples, kf2_index...etc.. I need all of the tuples (key,data) in my final dictionary.

I have:

import threading

from threading import Thread

However, I have no idea how to build this dictionary from the output of the function. There are only the 5 training set percentages, so how do I run these in parallel and build the dictionary?

 for i in range(len(train_set_percentages)):

Thread(target=generate_data_entry(train_set_percentages[i]))

Then...??

网友答案:

I found a solution in the link posted below the question. In order to produce a dictionary in the way I described above,

from threading import Thread

numbers = [1,2,3,4]
keys = ['one','two','three','four']

def add_to_dict(number,key,dict):
     dict[key] = number

n = 5 

dict_list = [{}] * 5
threads = [None] * 5

# run threads
for i in range(len(threads)):
    threads[i] = Thread(target=add_to_dict,args=(number[i],keys[i],dict_list[i]))
    threads[i].start()
for i in range(len(threads)):
    threads[i].join()

# merge dictionaries (using Python 3.5 syntax)
results = {}
for i in dict_list:
    results = {**results,**i}
分享给朋友:
您可能感兴趣的文章:
随机阅读: