Python: Categorizing Given Words by Their First Letters

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:
- Python 3: Convert Datetime to Timestamp and vice versa
- How to Install Python Libraries in Google Colab
- Tensorflow 2 – One Hot Encoding Examples
- Python program to count lower case letters in a string
You can also check out our Machine Learning category page or Python category page for more tutorials and examples.