How to group words by first letter in Python

2 Answers

0 votes
from collections import defaultdict

words = ["Python", "JavaScript", "C", "Java", "C#", "PHP", "C++", "Pascal", "SQL", "Rust"]

# defaultdict(list) automatically creates an empty list for any new key
group_words = defaultdict(list)

# Loop through each word in the list
for word in words:
    first_letter = word[0]          # Extract the first letter of the word
    group_words[first_letter].append(word)  # Add the word under its first letter

# Print each group using a loop
for letter, group in group_words.items():
    print(f"{letter}: {group}")     # Display the letter and its list of words


print(group_words)


'''
run:

P: ['Python', 'PHP', 'Pascal']
J: ['JavaScript', 'Java']
C: ['C', 'C#', 'C++']
S: ['SQL']
R: ['Rust']
defaultdict(<class 'list'>, {'P': ['Python', 'PHP', 'Pascal'], 'J': ['JavaScript', 'Java'], 'C': ['C', 'C#', 'C++'], 'S': ['SQL'], 'R': ['Rust']})

'''

 



answered Jan 15 by avibootz
0 votes
from collections import defaultdict

def group_by_first_letter(words):
    groups = defaultdict(list)

    for word in words:
        first_letter = word[0]
        groups[first_letter].append(word)

    return groups

def print_groups(groups):
    for letter, group in groups.items():
        print(f"{letter}: {group}")

def main():
    words = ["Python", "JavaScript", "C", "Java", "C#", "PHP",
             "C++", "Pascal", "SQL", "Rust"]

    grouped = group_by_first_letter(words)
    print_groups(grouped)
    print(grouped)   # raw defaultdict output, like your original code

main()



'''
run:

P: ['Python', 'PHP', 'Pascal']
J: ['JavaScript', 'Java']
C: ['C', 'C#', 'C++']
S: ['SQL']
R: ['Rust']
defaultdict(<class 'list'>, {'P': ['Python', 'PHP', 'Pascal'], 'J': ['JavaScript', 'Java'], 'C': ['C', 'C#', 'C++'], 'S': ['SQL'], 'R': ['Rust']})

'''

 



answered Jan 15 by avibootz
edited Jan 16 by avibootz
...