Python: Categorizing Given Words by Their First Letters

Last updated on November 10, 2022 Pennywise Loading... Post a comment

The Challenge

Let’s say we have a list of words and we want to put words into groups according to which letter they start with.

Hypothetical input:

['apple', 'ant', 'Komodo dragon', '']

Expected output:

  'a': ['apple', 'ant'],
  'k': ['Komodo dragon', ''

The result will be in the form of a dictionary whose each key is a letter and the corresponding value is a list of words.

The Solution

By using the dict.setdefault method, we can get the job done with a few lines of Python code. This method returns the value of the item with the specified key if that key exists. Otherwise, insert the key with a value of default and return default.


setdefault(key[, default])

The code:

words = ['apple', 'ant', 'bee', 'bat', 'bar', 'auto', '', 'Komodo dragon', 'Korea']

categorized_words = {}

for word in words:
    first_letter = word[0]
    categorized_words.setdefault(first_letter, []).append(word)



{'K': ['', 'Komodo dragon', 'Korea'],
 'a': ['apple', 'ant', 'auto'],
 'b': ['bee', 'bat', 'bar']}

Further reading:

You can also check out our Machine Learning category page or Python category page for more tutorials and examples.

Notify of
Inline Feedbacks
View all comments

You May Also Like