Reputation: 467
I have a python dict which has various keys such that dict.keys()=[1,2,3]
and each key holds an array of possibly different size such that dict[1] = [1,3,6], dict[2] = ['a', 'b'] dict[3] = [x]
. I want to have a new array where I get all possible combinations of the n
elements from each of the arrays.
For example, if the arrays were provided beforehand,
arr_1 = itertools.combinations(dict[1],n)
arr_2 = itertools.combinations(dict[2],n)
arr_3 = itertools.combinations(dict[3],n)
and then finally,
final = itertools.product(arr_1, arr_2, arr_3)
In a scenario where I do not the keys of the dict and the array sizes, how can I create the final
array ?
Upvotes: 1
Views: 87
Reputation: 401
Your question is a bit coarsely stated. If you are asking, how you can dynamically form the final array when you need to determine dict keys and values on the fly, you could do it like this:
def combo_dist(dict): # <--- dict is your starting dictionary
array = []
for v in dict.values(): # <--- all values from your dict
arrays.append(itertools.combination(v,len(v)))
# now array should be populated and you can make your final product:
final = itertools.product(*array)
return final
# now call this function:
final_array = combo_dict(your_dict)
now, if I understood correctly, this is the spelled out version of the algorithm. You could actually do a one-liner with list comprehension:
final_array = itertools.product(*[itertools.combinations(v, len(v)) for v in your_dict.values()])
but mind, that here the order of values is not deterministic. You may want to use sorted() as well in one of the steps. Depends on your needs.
Upvotes: 1
Reputation: 78690
If I understand correctly
itertools.product(*[itertools.combinations(v, min(n, len(v)) for v in dic.values()])
should do the trick.
edit: adjusted w.r.t. comments.
Upvotes: 2