Combinations from dictionary with list values using Python Combinations from dictionary with list values using Python python python

Combinations from dictionary with list values using Python


import itertools as itvarNames = sorted(variants)combinations = [dict(zip(varNames, prod)) for prod in it.product(*(variants[varName] for varName in varNames))]

Hm, this returns:

[{'debug': 'on', 'locale': 'de_DE'}, {'debug': 'on', 'locale': 'en_US'}, {'debug': 'on', 'locale': 'fr_FR'}, {'debug': 'off', 'locale': 'de_DE'}, {'debug': 'off', 'locale': 'en_US'}, {'debug': 'off', 'locale': 'fr_FR'}]

which is probably not exactly, what you want. Let me adapt it...

combinations = [ [ {varName: val} for varName, val in zip(varNames, prod) ] for prod in it.product(*(variants[varName] for varName in varNames))]

returns now:

[[{'debug': 'on'}, {'locale': 'de_DE'}], [{'debug': 'on'}, {'locale': 'en_US'}], [{'debug': 'on'}, {'locale': 'fr_FR'}], [{'debug': 'off'}, {'locale': 'de_DE'}], [{'debug': 'off'}, {'locale': 'en_US'}], [{'debug': 'off'}, {'locale': 'fr_FR'}]]

VoilĂ  ;-)


combinations = [[{key: value} for (key, value) in zip(variants, values)]                 for values in itertools.product(*variants.values())][[{'debug': 'on'}, {'locale': 'de_DE'}], [{'debug': 'on'}, {'locale': 'en_US'}], [{'debug': 'on'}, {'locale': 'fr_FR'}], [{'debug': 'off'}, {'locale': 'de_DE'}], [{'debug': 'off'}, {'locale': 'en_US'}], [{'debug': 'off'}, {'locale': 'fr_FR'}]]


This is what I use:

from itertools import productdef dictproduct(dct):    for t in product(*dct.itervalues()):        yield dict(zip(dct.iterkeys(), t))

which applied to your example gives:

>>> list(dictproduct({"debug":["on", "off"], "locale":["de_DE", "en_US", "fr_FR"]}))[{'debug': 'on', 'locale': 'de_DE'}, {'debug': 'on', 'locale': 'en_US'}, {'debug': 'on', 'locale': 'fr_FR'}, {'debug': 'off', 'locale': 'de_DE'}, {'debug': 'off', 'locale': 'en_US'}, {'debug': 'off', 'locale': 'fr_FR'}]

I find this is more readable than the one liners above.

Also, it returns an iterator like itertools.product so it leaves it up to the user whether to instantiate a list or just consume the values one at a time.