Python: Unique words and frequency from a given list of strings
21. Unique Words and Frequency Count from a List of Strings
Write a Python program to find all the unique words and count the frequency of occurrence from a given list of strings. Use Python set data type.
Sample Solution:
Python Code:
# Define a function 'word_count' that takes a list of words as input and returns a dictionary of word counts.
def word_count(words):
# Create a set 'word_set' to remove duplicate words from the input list.
word_set = set(words)
# Create an empty dictionary 'word_counts' to store word counts.
word_counts = {}
# Iterate over the unique words in 'word_set'.
for word in word_set:
# Count the occurrences of each word in the input list and store the count in 'word_counts'.
word_counts[word] = words.count(word)
# Return the 'word_counts' dictionary.
return word_counts
# Create a list 'words' with words of various colors.
words = ['Red', 'Green', 'Red', 'Blue', 'Red', 'Red', 'Green']
# Call the 'word_count' function with the 'words' list and print the word counts.
print(word_count(words))
Sample Output:
{'Red': 4, 'Blue': 1, 'Green': 2}
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to extract unique words from a list of strings using a set and then count their frequencies in the list.
- Write a Python program to use collections.Counter on a set derived from a list of strings to display word frequency.
- Write a Python program to iterate over a list of strings and build a frequency dictionary for unique words.
- Write a Python program to convert a list of strings into a set of unique words and then map each word to its count using a dictionary comprehension.
Python Code Editor:
Previous: Write a Python program to find the elements in a given set that are not in another set.
Next: Find all pairs in a list whose sum is equal to a target value.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.