Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match all combinations of list with other list

Tags:

python

I have 2 lists:

list1 = ['A', 'B', 'C']
list2 = ['1', '2', '3']

And I want to create a dictionary with all possible combinations of list2 with list1, something like:

output= [{'A':'1', 'B':'1', 'C':'1'},{'A':'2', 'B':'1', 'C':1'} ..., {'A':'3', 'B':'3', 'C':'3'}]

I tried:

combinations = ([dict(zip(list1,v)) for v in product(list2)])

But isn't what I expected

like image 219
LokoLokoNini Avatar asked Mar 03 '23 15:03

LokoLokoNini


1 Answers

import itertools

list1 = ['A', 'B', 'C']
list2 = ['1', '2', '3']
output = []
for p in itertools.product(list2, repeat=len(list1)):  # (1,1,1),(1,1,2),...,(3,3,3)
    # print (dict(zip(list1, p)))
    output.append(dict(zip(list1, p)))

print (output)

# One line
output = [dict(zip(list1, p)) for p in itertools.product(list2, repeat=len(list1))]

itertools.product returns all possible value-"pairs" you want, with the argument repeat denoting the length of each permutation(with repetition?)

like image 190
Gareth Ma Avatar answered Mar 11 '23 07:03

Gareth Ma