Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All possible permutations of dictionaries combinations out of 2 lists

Suppose I have 2 lists in python :

keys = [1, 2, 3, 4, 5, 6]

values = [7, 8, 9]

I want to get all permutations out of those 2 lists

something like:

d = [{1:7, 2:8, 3:9}, {1:8, 2:9, 3:7}, ....... ]

How could I achieve that?

like image 870
Hamdy Farag Avatar asked Dec 06 '22 15:12

Hamdy Farag


2 Answers

Do you mean something like this?

>>> import itertools
>>> keys = [1, 2, 3, 4, 5, 6]
>>> values = [7, 8, 9]
>>> d = [dict(zip(kperm, values)) for kperm in itertools.permutations(keys, len(values))]
>>> len(d)
120
>>> d[:10]
[{1: 7, 2: 8, 3: 9}, {1: 7, 2: 8, 4: 9}, {1: 7, 2: 8, 5: 9}, {1: 7, 2: 8, 6: 9}, {1: 7, 2: 9, 3: 8}, {1: 7, 3: 8, 4: 9}, {1: 7, 3: 8, 5: 9}, {1: 7, 3: 8, 6: 9}, {1: 7, 2: 9, 4: 8}, {1: 7, 3: 9, 4: 8}]
like image 138
DSM Avatar answered Dec 09 '22 16:12

DSM


>>>import itertools
>>>list(itertools.product(*[[1, 2, 3, 4, 5, 6],[7, 8, 9]]))
>>>[(1, 7), (1, 8), (1, 9), (2, 7), (2, 8), (2, 9), (3, 7), (3, 8), (3, 9), (4, 7), (4, 8), (4, 9), (5, 7), (5, 8), (5, 9), (6, 7), (6, 8), (6, 9)]
like image 25
fraxel Avatar answered Dec 09 '22 14:12

fraxel