Product of the Dictionary Values from Combinations of Dictionary Keys in Python

42 views Asked by At

I have a dictionary of sets in Python

dct={'k1':{1,2,3,4},'k2':{100,200},'k3':{1000,2000,3000,4000},'k4':{25,50}}

and I want to find the Cartesian product of all the possible combinations of, say 3 keys, so

'k1','k2','k3' >> product({1,2,3,4}, {100,200}, {1000,2000,3000,4000})
'k1','k2','k4'>> product({1,2,3,4}, {100,200}, {25,50})
etc

The code I’ve got below works, but doesn’t seem that pythonic and was wondering whether there was a more elegant solution, maybe using * to unpack the dictionary. My solution is fixed for 3 combinations, a general solution which could cater for n-combinations would be interesting...

for x,y,z in combinations(dct.keys(),3):
    for p in product(dct[x],dct[y],dct[z]):
1

There are 1 answers

1
Matthias On BEST ANSWER

Use the values in combinations. Get the return value in a tuple and unpack that tuple in the call to product.

from itertools import combinations, product

dct = {'k1': {1, 2, 3, 4}, 'k2': {100, 200}, 'k3': {1000, 2000, 3000, 4000},
       'k4': {25, 50}}

for combi in combinations(dct.values(), 3):
    for p in product(*combi):
        print(p)