Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combinations from dictionary with list values using Python

Tags:

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.

like image 953
Sebastian Werner Avatar asked Oct 06 '10 14:10

Sebastian Werner


People also ask

Can dictionary have list as values Python?

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.


2 Answers

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à ;-)

like image 87
eumiro Avatar answered Oct 21 '22 21:10

eumiro


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'}]] 
like image 44
tokland Avatar answered Oct 21 '22 23:10

tokland