2

if i have a dictionary:

d={
's':['a','b','c'], 
'v':['d','e'], 
'r':['g','h','i'],} 

(which could have an arbitrary number of keys)

how can i output a list of all the pair-wise combinations i.e.

['adg','adh', 'adi', 'aeg', 'aeh', 'aei', 'bdg', 'bdh', 'bdi', 'beg', 'beh', 'bei', 'cdg', 'cdh', 'cdi', 'ceg', 'ceh', 'cei']

i used:

l=list()
temp=''
for i in range(len(d['s'])):
    for j in range(len(d['v'])):
        for k in range(len(d['r'])):
            temp=d['s'][i]+d['v'][j]+d['r'][k]
            print(temp)
            l.append(temp)

but i need to make it generic for an arbitray number of keys.

thank you

1 Answers1

2

Use itertools.product and str.join in a list comprehension:

from itertools import product

out = [''.join(p) for p in product(*d.values())]

output:

['adg', 'adh', 'adi', 'aeg', 'aeh', 'aei',
 'bdg', 'bdh', 'bdi', 'beg', 'beh', 'bei',
 'cdg', 'cdh', 'cdi', 'ceg', 'ceh', 'cei']
mozway
  • 194,879
  • 13
  • 39
  • 75