Friday, September 5, 2025
HomeLanguagesPython – Occurrence counter in List of Records

Python – Occurrence counter in List of Records

Sometimes, while dealing with records we can have a problem in which we need count the occurrence of incoming digits corresponding to different characters/players in a game and compile them in a dictionary. This can have application in gaming and web development. Lets discuss a way in which this can be done. 
Method : Using loop + Counter() 
The combination of above functions can be used to perform this task. In this, we iterate for the elements and compute frequency using Counter() and unique characters are managed by keys of dictionary.
 

Python3




# Python3 code to demonstrate
# Occurrence counter in List of Records
# using Counter() + loop
from collections import Counter
 
# Initializing list
test_list = [('Gfg', 1), ('Gfg', 2), ('Gfg', 3), ('Gfg', 1), ('Gfg', 2), ('is', 1), ('is', 2)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Occurrence counter in List of Records
# using Counter() + loop
res = {}
for key, val in test_list:
    res[key] = [val] if key not in res else res[key] + [val]
 
res = {key: dict(Counter(val)) for key, val in res.items()}
 
# printing result
print ("Mapped resultant dictionary : " + str(res))


Output : 
The original list is : [(‘Gfg’, 1), (‘Gfg’, 2), (‘Gfg’, 3), (‘Gfg’, 1), (‘Gfg’, 2), (‘is’, 1), (‘is’, 2)] 
Mapped resultant dictionary : {‘is’: {1: 1, 2: 1}, ‘Gfg’: {1: 2, 2: 2, 3: 1}} 
 

Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. 
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32265 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11863 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6701 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS