Reputation: 97
I want a function of which the input is this:
my_dict = {
'foo':[1,2,3]
'bar': [True, False]
}
And the output is that:
results = {
'foo':[1, 1, 2, 2, 3, 3]
'bar': [True, False, True, False, True, False]
}
Context: I'm writing my own "cross-validation" function for machine learning. So I need to flatten all parameters to feed my model. I don't know in advance how many parameters there are neither their names. So I need to parse the input dictionary.
I feel like I'm making it more complicated than needed, so that's why I'm asking help. Maybe a function already exists to that, even if I didn't find it.
Thanks for your help!
Upvotes: 1
Views: 51
Reputation: 2434
A simple way to do it is the following
import itertools
keys = list(my_dict.keys())
product = list(itertools.product(*list(my_dict.values())))
results = {keys[i]: [item[i] for item in product] for i in range(len(keys))}
which gives the results you are after.
print(results)
{'foo': [1, 1, 2, 2, 3, 3], 'bar': [True, False, True, False, True, False]}
Upvotes: 6