Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate all combination from values in dict of lists in Python

I would like to generate all combinations of values which are in lists indexed in a dict:

{'A':['D','E'],'B':['F','G','H'],'C':['I','J']} 

Each time, one item of each dict entry would be picked and combined to items from other keys, so I have:

['D','F','I'] ['D','F','J'] ['D','G','I'] ['D','G','J'] ['D','H','I'] ... ['E','H','J'] 

I know there is a something to generate combinations of items in list in itertools but I don't think I can use it here since I have different "pools" of values.

Is there any existing solution to do this, or how should I proceed to do it myself, I am quite stuck with this nested structure.

like image 721
ibi0tux Avatar asked Aug 02 '16 13:08

ibi0tux


People also ask

How do you generate all possible combinations of two lists in Python?

The unique combination of two lists in Python can be formed by pairing each element of the first list with the elements of the second list. Method 1 : Using permutation() of itertools package and zip() function. Approach : Import itertools package and initialize list_1 and list_2.

How do you get all the keys values from a dict?

In Python to get all values from a dictionary, we can use the values() method. The values() method is a built-in function in Python and returns a view object that represents a list of dictionaries that contains all the values. In the above code first, we will initialize a dictionary and assign key-value pair elements.


2 Answers

import itertools as it  my_dict={'A':['D','E'],'B':['F','G','H'],'C':['I','J']} allNames = sorted(my_dict) combinations = it.product(*(my_dict[Name] for Name in allNames)) print(list(combinations)) 

Which prints:

[('D', 'F', 'I'), ('D', 'F', 'J'), ('D', 'G', 'I'), ('D', 'G', 'J'), ('D', 'H', 'I'), ('D', 'H', 'J'), ('E', 'F', 'I'), ('E', 'F', 'J'), ('E', 'G', 'I'), ('E', 'G', 'J'), ('E', 'H', 'I'), ('E', 'H', 'J')] 
like image 166
Maryam Avatar answered Sep 21 '22 18:09

Maryam


If you want to keep the key:value in the permutations you can use:

import itertools keys, values = zip(*my_dict.items()) permutations_dicts = [dict(zip(keys, v)) for v in itertools.product(*values)] 

this will provide you a list of dicts with the permutations:

print(permutations_dicts) [{'A':'D', 'B':'F', 'C':'I'},   {'A':'D', 'B':'F', 'C':'J'},  ...  ] 

disclaimer not exactly what the OP was asking, but google send me here looking for that.

like image 41
Pablo Avatar answered Sep 21 '22 18:09

Pablo