0

I have a dictionary with keys. The keys are tuple of two.

dict_keys([(), ('cHW',), ('cHWtil',), ('cHW', 'cHW'), ('cHWtil', 'cHWtil'),('cHW', 'cHWtil'))

However the tuple can also be a combination of a string and an empty element.

If I want to create the same keys by using iterables.product I am not sure how I can get the same keys, because I can't produce the keys in which there is only one string and comma nothing like in the dictionary keys above.

For example if I write the following I get:

coefficients=[(), ('cHW'), ('cHWtil')]
coefficient_combinations=itertools.product(coefficients, repeat=2)
list(coefficient_combinations)
[((), ()),
 ((), 'cHW'),
 ((), 'cHWtil'),
 ('cHW', ()),
 ('cHW', 'cHW'),
 ('cHW', 'cHWtil'),
 ('cHWtil', ()),
 ('cHWtil', 'cHW'),
 ('cHWtil', 'cHWtil')]

Which doesn't for example contain the first key in the list I showed at the beginning, because I get these brackets.

eeqesri
  • 217
  • 1
  • 2
  • 9
  • If your desired result has 6 items, it's not a cartesian product which has 9 items. – mkrieger1 Jul 02 '22 at 09:32
  • @mkrieger1 I know. I can filter the ones I need not. but in this question, the important thing is to generate the ones like the first three in the list at the beginning. – eeqesri Jul 02 '22 at 09:34
  • Also your input consists of 1 tuple and 2 strings. Maybe you should first set that straight so that it is 3 tuples. – mkrieger1 Jul 02 '22 at 09:36
  • @mkrieger1 Well that's exactly the problem. The first dict_key contains an empty tuple and tuples with strings comma None. But I don't know how to generate those like the way I tried with coefficients=[(), ('cHW'), ('cHWtil')] – eeqesri Jul 02 '22 at 09:40

1 Answers1

2

What you're looking for is combinations_with_replacement().

Then, for loop on the size like so:

>>> coefficients=['cHW', 'cHWtil']
>>> combs = itertools.chain.from_iterable(itertools.combinations_with_replacement(coefficients, i) for i in range(3))
>>> list(combs)
[(), ('cHW',), ('cHWtil',), ('cHW', 'cHW'), ('cHW', 'cHWtil'), ('cHWtil', 'cHWtil')]

If what you're actually looking for is the powerset, please see this answer.


Alternative implementation:

combs = [c for i in range(3) for c in itertools.combinations_with_replacement(coefficients, i)]

I prefer the top, but up to you.

Bharel
  • 23,672
  • 5
  • 40
  • 80