Simple utility function that can transform the values in a dictionary into a new dictionary using multiple threads, if used with Python Multiprocessing.
Copy the content of the attached dict_pool_map.py
-file. A non-typed version is also attached to showcase an easy-to-read implementation (dict_pool_map_no_typing.py
).
import multiprocessing
import time
def double_it(x: int) -> int:
time.sleep(1)
return x * 2
inp = {1: 1, 2: 2, 3: 3}
with multiprocessing.Pool() as p:
out = dict_pool_map(p, double_it, inp)
print(out) # {1: 2, 2: 4, 3: 6}
NOTE: For non-concurrent workloads, use a dictionary comprehension instead.
out = {key: double_it(value) for key, value in inp.items()}