2

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...??

Chris
  • 28,822
  • 27
  • 83
  • 158
  • 1
    http://stackoverflow.com/questions/6893968/how-to-get-the-return-value-from-a-thread-in-python – David Zemens Mar 27 '16 at 15:02
  • Ok, thanks for that...as this is upvoted, I can't delete. I'll see if I can construct an answer and turn this into a generic how to with the dictionary search tag. – Chris Mar 27 '16 at 20:21

1 Answers1

3

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}
Chris
  • 28,822
  • 27
  • 83
  • 158