Match all combinations of list with other list

Viewed 288

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

4 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?)

  • You can use itertools.product.
  • The following solution is scalable for any list1 and list2 size.
from itertools import product

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

pro = list(product(list2, repeat=len(list1)))

combinations = [dict(zip(list1, p)) for p in pro ]

print(ombinations)

Since you know that the keys in the dictionaries will always be the same, you could try something like this:

list_of_dicts = []
for i in range(1, 4):
    for j in range(1, 4):
        for k in range(1, 4):
            list_of_dicts.append({'A':str(i), 'B':str(j), 'C':str(k)})

You can use recursion for a no-import solution:

list1 = ['A', 'B', 'C']
list2 = ['1', '2', '3']
def combos(d, c = []):
  if len(c) < len(d):
     yield from [i for b in d for i in combos(d, c+[b])]
  else:
     yield dict(zip(list1, c))

print(list(combos(list2)))

Output:

[{'A': '1', 'B': '1', 'C': '1'}, {'A': '1', 'B': '1', 'C': '2'}, {'A': '1', 'B': '1', 'C': '3'}, {'A': '1', 'B': '2', 'C': '1'}, {'A': '1', 'B': '2', 'C': '2'}, {'A': '1', 'B': '2', 'C': '3'}, {'A': '1', 'B': '3', 'C': '1'}, {'A': '1', 'B': '3', 'C': '2'}, {'A': '1', 'B': '3', 'C': '3'}, {'A': '2', 'B': '1', 'C': '1'}, {'A': '2', 'B': '1', 'C': '2'}, {'A': '2', 'B': '1', 'C': '3'}, {'A': '2', 'B': '2', 'C': '1'}, {'A': '2', 'B': '2', 'C': '2'}, {'A': '2', 'B': '2', 'C': '3'}, {'A': '2', 'B': '3', 'C': '1'}, {'A': '2', 'B': '3', 'C': '2'}, {'A': '2', 'B': '3', 'C': '3'}, {'A': '3', 'B': '1', 'C': '1'}, {'A': '3', 'B': '1', 'C': '2'}, {'A': '3', 'B': '1', 'C': '3'}, {'A': '3', 'B': '2', 'C': '1'}, {'A': '3', 'B': '2', 'C': '2'}, {'A': '3', 'B': '2', 'C': '3'}, {'A': '3', 'B': '3', 'C': '1'}, {'A': '3', 'B': '3', 'C': '2'}, {'A': '3', 'B': '3', 'C': '3'}]
Related