Python: Categorizing Given Words by Their First Letters

Last updated on November 10, 2021 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', 'Kindacode.com']

Expected output:

{
  'a': ['apple', 'ant'],
  'k': ['Komodo dragon', 'Kindacode.com'
}

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.

Syntax:

setdefault(key[, default])

The code:

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

categorized_words = {}

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

categorized_words

Output:

{'K': ['Kindacode.com', '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.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like