Skip to content

Latest commit

 

History

History
89 lines (66 loc) · 1.38 KB

File metadata and controls

89 lines (66 loc) · 1.38 KB
title Group Words by First Letter

Problem Statement

Write a function that takes a list of words and groups them by their first letter into a dictionary.

Example Example Input:
['apple', 'banana', 'apricot', 'blueberry', 'cherry']

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


Solution

<template>
from collections import defaultdict

def group_by_first_letter(words):
    
<sol>
    grouped = {}
    for word in words:
        first_letter = word[0].lower()
        if first_letter not in grouped:
            grouped[first_letter] = []
        grouped[first_letter].append(word)
    return grouped
</sol>
</template>
<suffix>
#Driver code
l=eval(input())
print(group_by_first_letter(l))
</suffix>

Public Test Cases

Input 1

['apple', 'banana', 'apricot', 'blueberry', 'cherry']

Output 1

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

Input 2

['dog', 'deer', 'cat', 'camel']

Output 2

{'d': ['dog', 'deer'], 'c': ['cat', 'camel']}

Private Test Cases

Input 1

['kiwi', 'kangaroo', 'kiwi', 'kiwi']

Output 1

{'k': ['kiwi', 'kangaroo', 'kiwi', 'kiwi']}

Input 2

[]

Output 2

{}