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.
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.
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.
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')]
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.
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