Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,560 questions

51,419 answers

573 users

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 1 day ago 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 1 day ago by avibootz
edited 13 hours ago by avibootz
...