Can I get a generalize approach for this question?

Viewed 52

I used itertools and for loop as well, but I'm not sure what would be the pattern with more than 2 keys, as with itertools, for 3 keys, I'm getting one list element from each corresponding key,

d = {‘1’: ['a','b'], '2':['c','d'], '3' : ['m']}

output : acm adm bcm bdm

or should the output be: ac ad am bc bd bm cm dm

Q. Write a Python program to create and display all combinations of letters, selecting each letter from a different key in a dictionary.

Sample data: {‘1’: ['a','b'], '2':['c','d']}
expected Output: 
ac
ad
bc
bd

My Code:-

dic = { '1' : ['a', 'b', '8'], '2' : ['c', 'd', 'm']}
i = 0;
key1 = list(dic.keys())[0]
key2 = list(dic.keys())[1]


for i in range(len(dic[key1])):

    for j in range(len(dic[key2])):
        print(dic[key1][i], end = "")
        print(dic[key2][j])

output:-

ac ad am bc bd bm 8c 8d 8m
2 Answers

If you want to use itertools combinations, in your example, you should explore something like :

from itertools import combinations 
dic1 = ['a', 'b', '8']
dic2 = ['c', 'd', 'm']
for i in dic1:
    for j in dic2:
        for k in combinations(i+j,2):
            print(k)

If you want to extrapolate to 3 lists, you should do something like:

from itertools import combinations 
dic1 = ['a', 'b']
dic2 = ['c', 'd']
dic3 = ['m']
for i in (dic1):
    for j in dic2:
        for k in dic3:
            for l in combinations(i+j+k,3):
                print(l)

And as I don't exactly understand what is your expectation, for the last possibility of your examples, here is what you should perhaps do for 2 combination in 3 lists:

from itertools import combinations 
dic1 = ['a', 'b']
dic2 = ['c', 'd']
dic3 = ['m']
for i in (dic1):
    for j in dic2:
        for k in dic3:
            for l in combinations(i+j+k,2):
                print(l)

This code is not optimized for high performance, but it's much to understand the behavior of combinations from itertools

You can use a mix of itertools.combinations and itertools.product

from itertools import combinations, product

d = {'1': ['a','b'], '2':['c','d'], '3' : ['m']}

[''.join(p) for c in combinations(d.values(), 2) for p in product(*c)]
# ['ac', 'ad', 'bc', 'bd', 'am', 'bm', 'cm', 'dm']
Related