Ivan
Ivan

Reputation: 117

How can I list all possible 3 letter combinations from dict.items()?

I'm making a consecutive letter checker and I got this problem and its supposed to return all the triple letter combinations from the keyboard, however, I don't understand what I'm doing wrong with the last part and how I could make it work? I can only get it to print the 3 letter combinations for the key() not the items() in the dict. The result I'm looking for is all possible 3 letter combinations from the 'items()' to be printed out in a list.

keyboard = {'line1':'qwertyuiop',
            'line2':'asdfghjkl',
                'line3':'zxcvbnm'}

def consequ(key):
    a = []
    for each_key in key:
        for i in range(len(key[each_key])-2):
            a.append(each_key[i:i+3])
    return a

I call the function by writing

consequ(keyboard)

The output is given by this code:

['lin', 'ine', 'ne1', 'e1', '1', '', '', '', 'lin', 'ine', 'ne2', 'e2', '2', '', '', 'lin', 'ine', 'ne3', 'e3', '3']

The wanted output is:

['qwe', 'wer', 'ert', 'rty', 'tyu', 'yui', 'uio', 'iop', 'asd', 'sdf', 'dfg', 'fgh', 'ghj', 'hjk', 'jkl', 'zxc', 'xcv', 'cvb', 'vbn', 'bnm']

Upvotes: 1

Views: 225

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477318

If you want to store all these combinations of keyboards, you have to iterate over the values of the dictionary. You write however:

a.append(each_key[i:i+3])
#        ^ key of the dictionary

So you have to rewrite it to:

def consequ(key):
    a = []
    for line in key.values():
        for i in range(len(line)-2):
            a.append(line[i:i+3])
    return a

Or more elegant:

def consequ(key):
    a = []
    for line in key.values():
        a += [line[i:i+3] for i in range(len(line)-2)]
    return a

These generate:

>>> consequ(keyboard)
['zxc', 'xcv', 'cvb', 'vbn', 'bnm', 'asd', 'sdf', 'dfg', 'fgh', 'ghj', 'hjk', 'jkl', 'qwe', 'wer', 'ert', 'rty', 'tyu', 'yui', 'uio', 'iop']

Note that most Python interpreters have unordered dictionaries, so the order of the lines can be different.

Upvotes: 2

Related Questions