0

I'm developing a function func(lvars,lconsts) that, given a list with all variables in a certain operator and a list with all constants in the current state, computes a list with all possible assignments of constants to variables.

func(['X','Y'],['a','b'])

The expected output:

[{'X':'a','Y':'a'},{'X':'b','Y':'a'},{'X':'a','Y':'b'},{'X':'b','Y':'b'}]

I tried to use itertools like this:

def func(lvars,lconsts):
    return list(itertools.product(lvars, lconsts))

but instead of the expected output im getting this:

[('X', 'a'), ('X', 'b'), ('Y', 'a'), ('Y', 'b')]
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
Duarte Castanho
  • 305
  • 2
  • 6
  • 20
  • How about passing it into a `dict()` constructor instead of a `list()` constructor? – G. Anderson Oct 26 '18 at 18:57
  • 1
    See this identical question posted minutes ago: https://stackoverflow.com/questions/53013948/every-possible-combination-of-two-lists#comment92931442_53013948 – Patrick Haugh Oct 26 '18 at 18:58
  • "I tried to use itertools like this:" What you want to do is generate the possible *sequences of values* for the dicts (i.e. `[('a', 'a'), ('a', 'b'), ('b', 'a'), ('b', 'b')]`) using `itertools.product`, and then make the dicts from them (by using the first element in each tuple as the `X` value and the second element as the `Y` value. That means, you want a product of the `['a','b']` list **with itself**, for as many times as there are elements in the list of keys. After that, it's a straightforward matter of making a dict from the key list with each value tuple. – Karl Knechtel Mar 02 '23 at 01:13
  • Please see the linked duplicates for details. – Karl Knechtel Mar 02 '23 at 01:16

1 Answers1

0

How about passing it into a dict() constructor instead of a list() constructor?

def func(lvars,lconsts):
    return dict(product(lvars, lconsts))
G. Anderson
  • 5,815
  • 2
  • 14
  • 21