I have the following incoming value:
variants = {   "debug" : ["on", "off"],   "locale" : ["de_DE", "en_US", "fr_FR"],   ... }   I want to process them so I get the following result:
combinations = [   [{"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 should work with arbitrary length of keys in the dictionary. Played with itertools in Python, but did not found anything matching these requirements.
It definitely can have a list and any object as value but the dictionary cannot have a list as key because the list is mutable data structure and keys cannot be mutable else of what use are they.
import itertools as it  varNames = 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'}]] 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With