Python – Group Similar Start and End character words

Sometimes, while working with Python data, we can have problem in which we need to group all the words on basis of front and end characters. This kind of application is common in domains in which we work with data like web development. Lets discuss certain ways in which this task can be performed.

Method #1 : Using defaultdict() + loop
The combination of above functions can be used to perform this task. In this, we check for front and last element using string slice notations and store in dict. with first and last character as key.





# Python3 code to demonstrate working of 
# Group Similar Start and End character words
# Using defaultdict() + loop
from collections import defaultdict
def end_check(word):
    sub1 = word.strip()[0]
    sub2 = word.strip()[-1]
    temp = sub1 + sub2
    return temp
def front_check(word):
    sub = word.strip()[1:-1]
    return sub
# initializing string
test_str = 'geeksforgeeks is indias best and bright for geeks'
# printing original string
print("The original string is : " + str(test_str))
# Group Similar Start and End character words
# Using defaultdict() + loop
test_list = test_str.split()
res = defaultdict(set)
for ele in test_list:
# printing result 
print("The grouped dictionary is : " + str(dict(res))) 


Output :

The original string is : geeksforgeeks is indias best and bright for geeks
The grouped dictionary is : {‘fr’: {‘o’}, ‘bt’: {‘righ’, ‘es’}, ‘ad’: {‘n’}, ‘gs’: {‘eeksforgeek’, ‘eek’}, ‘is’: {”, ‘ndia’}}


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.