Here's a way using list comprehensions and itertools.product
:
from itertools import product, chain
d = {'A': 3, 'B': 1}
l = [[k*i for i in range(1,v+1)] for k, v in d.items()]
[''.join(element) for element in product(*l)] + list(chain.from_iterable(l))
Output:
['AB', 'AAB', 'AAAB', 'A', 'AA', 'AAA', 'B']
Details:
The result of the first list comprehension is a nested list where each sublist has each of the keys
contained in the dictionary repeated from 1
up to its corresponding value
:
[['A', 'AA', 'AAA'], ['B']]
The second one, performs the cartesian product using itertools.product
, and each product is joined
into a string. Finally a flattened version of l
is added using chain.from_iterable
:
print(list(chain.from_iterable(l)))
['A', 'AA', 'AAA', 'B']
[''.join(element) for element in product(*l)]
['AB', 'AAB', 'AAAB']