Find the first repeated word in a string in Python using Dictionary

In a given sentence there may be a word which get repeated before the sentence ends. In this python program, we are going to catch such word which is repeated in sentence. Below is the logical steps we are going to follow to get this result.

  • Splits the given string into words separated by space.
  • Then we convert these words into Dictionary using collections
  • Traverse this list of words and check which first word has the frequency > 1

Program - Find the Repeated Word

In the below program we use the counter method from the collections package to keep a count of the words.


 Live Demo

from collections import Counter
def Repeat_word(load):
   word = load.split(' ')
   dict = Counter(word)
   for value in word:
      if dict[value]>1:
         print (value)
if __name__ == "__main__":
   input = 'In good time in bad time friends are friends'

Running the above code gives us the following result −



Updated on: 19-Dec-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started