'More elegant way to create a python dictionary from a map object and list
someList=['this','that','the_other','and_this']
timeFrame='hour'
getDatafromFile(some_string,time_frame):
do some processing
return dataframeObject
The end result is a dictionary with a keyed on the strings from someList and a value of the object returned from getDatafromFile. The following code I wrote accomplishes this but it seems there should be an easier way with less lines of code.
with ThreadPoolExecutor() as executor:
results=executor.map(getDatafromFile, [*someList],[timeFrame for i in range(len(someList))])
from this point forward is there a more elegant way to do this with less lines of code? Some sort of comprehension, perhaps. I thought about returning the string value and dataframe object back from the function, but it seems asinine to return back a parameter.
pdDataList=[]
for result in results:
pdDataList.append(result)
df_dict=dict(zip(someList,pdDataList))
Solution 1:[1]
You can use dict comprehension syntax:
{key: getDatafromFile(key, timeFrame) for key in someList}
Solution 2:[2]
From the answer below, which can't work because the function has to be called by the threadpool executor, I got the idea of how to do the four lines of code in one line. Apparently a map object can be iterated as if it's a list. I'm sure there's a dictionary comprehension equivalent but this is just as simple of a one liner:
df_dict=dict(zip(someList,results))
Thus the entire code is:
with ThreadPoolExecutor() as executor:
results=executor.map(getDatafromFile, [*someList],[timeFrame for i in range(len(someList))])
df_dict=dict(zip(someList,results))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nechoj |
| Solution 2 | horsehead97 |
