Find the first repeated word in a string in Python using Dictionary Last Updated : 10 Apr, 2025 Comments Improve Suggest changes Like Article Like Report We are given a string that may contain repeated words and the task is to find the first word that appears more than once. For example, in the string "Learn code learn fast", the word "learn" is the first repeated word. Let's understand different approaches to solve this problem using a dictionary. Using in keywordThe in keyword is used to check whether a specific key exists in a dictionary. It returns a boolean value True if the key is found and False otherwise. This is a safe and efficient way to prevent errors when working with dictionaries, especially before accessing or modifying a key. Python import re t = "Learn code learn fast" # Get lowercase words w = re.findall(r'\b\w+\b', t.lower()) d = {} for x in w: # If repeated, print and stop if x in d: print(x) break else: # Mark as seen d[x] = 1 Outputlearn Explanation: A dictionary tracks seen words. As each word is checked, if it's already in the dictionary, it's printed as the first repeat and the loop stops. Otherwise, it's added to the dictionary.Using get() methodget() method is used to retrieve the value for a given key from a dictionary. If the key does not exist, it returns None by default or a value you specify. This method is helpful when you want to avoid exceptions and provide fallback values during lookups, such as when counting word occurrences. Python import re t = "Python is great and Python is easy" # Get lowercase words w = re.findall(r'\b\w+\b', t.lower()) c = {} for x in w: # Count words and check for second occurrence c[x] = c.get(x, 0) + 1 if c[x] == 2: print(x) break Outputpython Explanation: A dictionary is used to count how many times each word appears. As the loop iterates through each word, the get() method updates its count. When a word's count becomes 2, it is identified as the first word that repeats.Using setdefault()The setdefault() method checks if a key exists in a dictionary and if not, it inserts the key with a specified default value. It then returns the value for that key regardless of whether it was newly added or already present. This is particularly useful for initializing keys in dictionaries, especially in counting or grouping scenarios. Python import re t = "Data science is data driven" # Get lowercase words w = re.findall(r'\b\w+\b', t.lower()) s = {} for x in w: # If seen before, print and stop if s.setdefault(x, 0): print(x) break s[x] += 1 Outputdata Explanation: setdefault() method initializes each word with a count of 0 if it's not already in the dictionary. If the word has been seen before (i.e., its value is non-zero), it is printed as the first repeated word and the loop stops. Otherwise, its count is incremented. Comment More infoAdvertise with us Next Article Find the first repeated word in a string in Python using Dictionary S Shashank Mishra Follow Improve Article Tags : Strings Python DSA python-dict python-string Python dictionary-programs Python string-programs +3 More Practice Tags : pythonpython-dictStrings Similar Reads Scraping And Finding Ordered Words In A Dictionary using Python What are ordered words? An ordered word is a word in which the letters appear in alphabetic order. For example abbey & dirt. The rest of the words are unordered for example geeksThe task at hand This task is taken from Rosetta Code and it is not as mundane as it sounds from the above description 3 min read Second most repeated word in a sequence in Python Given a sequence of strings, the task is to find out the second most repeated (or frequent) string in the given sequence. (Considering no two words are the second most repeated, there will be always a single word). Examples: Input : {"aaa", "bbb", "ccc", "bbb", "aaa", "aaa"} Output : bbb Input : {"g 4 min read Python - Find dictionary keys present in a Strings List Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the extraction of dictionary keys from strings list feeded. This problem can have application in many domains including data. Lets discuss certain ways in which this task can be performed. Method #1: U 7 min read Find frequency of each word in a string in Python Write a python code to find the frequency of each word in a given string. Examples: Input : str[] = "Apple Mango Orange Mango Guava Guava Mango" Output : frequency of Apple is : 1 frequency of Mango is : 3 frequency of Orange is : 1 frequency of Guava is : 2 Input : str = "Train Bus Bus Train Taxi A 7 min read Python | Words extraction from set of characters using dictionary Given the words, the task is to extract different words from a set of characters using the defined dictionary. Approach: Python in its language defines an inbuilt module enchant which handles certain operations related to words. In the approach mentioned, following methods are used. check() : It che 3 min read Find the most repeated word in a text file Python provides inbuilt functions for creating, writing, and reading files. Two types of files can be handled in python, normal text files, and binary files (written in binary language,0s and 1s). Text files: In this type of file, Each line of text is terminated with a special character called EOL ( 2 min read Find all strings that match specific pattern in a dictionary Given a dictionary of words, find all strings that match the given pattern where every character in the pattern is uniquely mapped to a character in the dictionary. Examples: Input: dict = ["abb", "abc", "xyz", "xyy"]; pattern = "foo" Output: [xyy abb] xyy and abb have same character at index 1 and 15+ min read Kâth Non-repeating Character in Python We need to find the first K characters in a string that do not repeat within the string. This involves identifying unique characters and their order of appearance. We are given a string s = "geeksforgeeks" we need to return the non repeating character from the string which is 'r' in this case. This 4 min read Python - Separate first word from String We need to write a Python program to split a given string into two parts at the KáµÊ° occurrence of a specified character. If the character occurs fewer than K times, return the entire string as the first part and an empty string as the second part. Separating the first word from a string involves ide 2 min read Check if String Contains Substring in Python This article will cover how to check if a Python string contains another string or a substring in Python. Given two strings, check whether a substring is in the given string. Input: Substring = "geeks" String="geeks for geeks"Output: yesInput: Substring = "geek" String="geeks for geeks"Output: yesEx 8 min read Like