Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading