1

I have two lists:

object = ['square','circle','triangle']
description = ['red','green']

I want as output a list of dictionaries:

{'square': 'red', 'circle': 'red', 'triangle': 'red'}
{'square': 'red', 'circle': 'red', 'triangle': 'green'}
{'square': 'green', 'circle': 'red', 'triangle': 'green'}

etc.

So the objects don't repeat, but the descriptions may. Each dictionary has as its keys the original list of objects.

I'm not sure of the name of the algorithm I want, so I'm having trouble finding the correct one. (I've looked at permutations of two lists in python, but that's seeking a different result. Permutations of two lists is the same question, but using OCAML.)

Ollyver
  • 359
  • 2
  • 14
  • This question is a duplicate of "Cartesian product giving a dictionary", but not of "Operation on every pair of element in a list". – Ollyver Jun 03 '17 at 15:14
  • BTW, you shouldn't use `object` as a variable name because that shadows the built-in `object` type. It won't hurt anything here, but it looks weird in a decent syntax highlighter. And it will cause weird error messages if the subsequent code uses Python 2 new-style class definitions: `class MyClass(object):`. – PM 2Ring Jun 03 '17 at 15:18
  • I made some wrong comments initially, fixed some wrong duplicate closures with other wrong ones, re-read, and then fixed the duplicate links properly. – Karl Knechtel Mar 02 '23 at 02:57

1 Answers1

5

You could use itertools.product to generate all possible combinations of your descriptions.

Then create a dictionary with the objects as keys and the "combination" as values:

>>> import itertools

>>> objects = ['square','circle','triangle']
>>> description = ['red','green']

>>> [dict(zip(objects, comb)) for comb in itertools.product(description, repeat=len(objects))]
[{'circle': 'red', 'square': 'red', 'triangle': 'red'},
 {'circle': 'red', 'square': 'red', 'triangle': 'green'},
 {'circle': 'green', 'square': 'red', 'triangle': 'red'},
 {'circle': 'green', 'square': 'red', 'triangle': 'green'},
 {'circle': 'red', 'square': 'green', 'triangle': 'red'},
 {'circle': 'red', 'square': 'green', 'triangle': 'green'},
 {'circle': 'green', 'square': 'green', 'triangle': 'red'},
 {'circle': 'green', 'square': 'green', 'triangle': 'green'}]
MSeifert
  • 145,886
  • 38
  • 333
  • 352