Python – Case Insensitive string counter
Given a list of strings, find the frequency of strings case insensitive.
Input : test_list = ["Gfg", "Best", "GFG", "is", "IS", "BEST"]
Output : {'gfg': 2, 'best': 2, 'is': 2}
Explanation : All occur twice. Input : test_list = ["Gfg", "gfg", "GFG"]
Output : {'gfg': 3}
Explanation : Only "gfg" 3 occurrences.Method 1: Using defaultdict() + lower()
In this, we perform lower() to all the strings, before mapping in defaultdict. This ensures case insensitivity while mapping and cumulating frequency.
Python3
# Python3 code to demonstrate working of# Strings Frequency (Case Insensitive)# Using defaultdict() + lower()from collections import defaultdict# initializing listtest_list = ["Gfg", "Best", "best", "gfg", "GFG", "is", "IS", "BEST"]# printing original listprint("The original list is : " + str(test_list))res = defaultdict(int)for ele in test_list: # lowercasing to cater for Case Insensitivity res[ele.lower()] += 1# printing resultprint("Strings Frequency : " + str(dict(res))) |
Output
The original list is : ['Gfg', 'Best', 'best', 'gfg', 'GFG', 'is', 'IS', 'BEST']
Strings Frequency : {'gfg': 3, 'best': 3, 'is': 2}Time Complexity: O(n)
Auxiliary Space: O(n)
Method 2: Using count() method
Python3
# Python3 code to demonstrate working of# Strings Frequency (Case Insensitive)# initializing listtest_list = ["Gfg", "Best", "best", "gfg", "GFG", "is", "IS", "BEST"]# printing original listprint("The original list is : " + str(test_list))x = []res = dict()for i in test_list: x.append(i.lower())a = list(set(x))for i in a: res[i] = x.count(i)# printing resultprint("Strings Frequency : " + str(dict(res))) |
Output
The original list is : ['Gfg', 'Best', 'best', 'gfg', 'GFG', 'is', 'IS', 'BEST']
Strings Frequency : {'best': 3, 'is': 2, 'gfg': 3}




Please Login to comment...