Python - Create a Dictionary with Key as First Character and Value as Words Starting with that Character

Python - Create a Dictionary with Key as First Character and Value as Words Starting with that Character

Creating a dictionary where keys are the first characters of words and values are lists of words that start with those characters is a common data organization task. In this tutorial, we'll walk you through the process of achieving this using Python.

Example:

List of Words: ["apple", "banana", "cherry", "apricot", "blueberry", "ananas"]

Resulting Dictionary:

{ 'a': ['apple', 'apricot', 'ananas'], 'b': ['banana', 'blueberry'], 'c': ['cherry'] } 

Approaches:

1. Using a for loop:

Iterate through each word in the list and populate the dictionary:

words = ["apple", "banana", "cherry", "apricot", "blueberry", "ananas"] dictionary = {} for word in words: # Get the first letter of the word key = word[0] # If the key doesn't exist in the dictionary, create it if key not in dictionary: dictionary[key] = [] # Append the word to the appropriate list dictionary[key].append(word) print(dictionary) 

2. Using defaultdict from collections:

defaultdict allows us to provide a default value for the dictionary if the key doesn't exist:

from collections import defaultdict words = ["apple", "banana", "cherry", "apricot", "blueberry", "ananas"] dictionary = defaultdict(list) for word in words: dictionary[word[0]].append(word) print(dict(dictionary)) 

3. Using Dictionary Comprehension:

This provides a more concise method, but it's slightly tricky due to the necessity to ensure lists for each key:

words = ["apple", "banana", "cherry", "apricot", "blueberry", "ananas"] dictionary = {word[0]: [] for word in words} for word in words: dictionary[word[0]].append(word) print(dictionary) 

Notes:

  1. These methods automatically generate keys for the first character of each word and add words to lists based on that character. If you have a mixture of upper and lower case words and wish to treat them as the same, ensure you convert the words to a common case using .lower() or .upper().

  2. The defaultdict approach is particularly elegant when populating dictionaries with lists, as it automatically handles the creation of new lists when encountering a new key.

By following these methods, you can efficiently create a dictionary where keys represent the first character of words and values are lists of words starting with those characters.


More Tags

webgl alassetslibrary undefined-reference fragment-tab-host reference hardware-acceleration e-commerce cloud-foundry interop ecmascript-2016

More Programming Guides

Other Guides

More Programming Examples