Write a function named initialLetters that takes one paramete

Write a function named initialLetters that takes one parameter, wordList – a list of words.
Create and return a dictionary in which each initial letter of a word in wordList is a key and the
corresponding value is a list of the words in wordList that begin with that letter. There should be no
duplicate words in any value in the dictionary.

Think through the problem and break out the steps needed to first, create a set of keys from the first letters in the list. create a dictionary of those keys with their value set initially to an empty list, then iterate over the keys and over a copy of word_list to build up the data in each key.

initialLetters.py
def initialLetters(word_list):
    same_first = {}
    keys = set(map(lambda x: x[0], word_list))
    for key in keys: same_first[key] = []
    for key in same_first:
      for word in word_list[:]:
        if word[0] == key:
          same_first[key].append(word_list.pop(word_list.index(word)))
    return same_first
print (initialLetters(['and','apple','beer', 'boar','cat', 'coat', 'dog', 'dig', 'echo', 'edge']))
{'a': ['and', 'apple'], 'd': ['dog', 'dig'], 'c': ['cat', 'coat'], 'e': ['echo', 'edge'], 'b': ['beer', 'boar']}

There are lots of ways to skin a cat, take the time to work up a solution of your own so you get the learning experience and pride in your accomplishment.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.