How To Make A Counter In Python

The python Counter class in the Collections package is a very useful tool class, which can automatically count the number of occurrences of each element in the container. The essence of Counter is a special python dictionary object, except that its keys are all the elements it contains, and its value records the number of occurrences of the key. Therefore, if the value is accessed through a key that does not exist in the Counter, 0 will be returned, which means that the key has appeared 0 times.

You can create a Counter object through any iterable object parameter. At that time, the Counter will automatically count the number of occurrences of each element and use the element as the key and the number of occurrences as the value to construct the Counter object. You can also construct a Counter object with a python dictionary object as a parameter or through keyword-value pair arguments. Below are some examples.

1. Python Create Counter Example.

  1. The below example shows you how to create a python counter object.
    from collections import Counter
    
    
    def create_python_counter():
        
        # create an empty Counter object.
        c_1 = Counter()
        print(c_1)
        
        # create a Counter object by an iterable object ( a string ).
        c_2 = Counter('I love python counter class')
        print(c_2)
        
        # create a Counter object by a an arrary.
        c_3 = Counter(['I', 'love', 'python', 'counter', 'class'])
        print(c_3)
        
        # create a Counter object by a python dictionary object.
        c_4 = Counter({'who':'I', 'action':'love', 'what':'python'})
        print(c_4)
        
        # create a Counter object by key-value pair arguments.
        c_5 = Counter(who='I', action='love', what='python')
        print(c_5)
    
    if __name__ == '__main__':
        
        create_python_counter()
    
  2. Below is the above example code output.
    Counter()
    Counter({' ': 4, 'o': 3, 'l': 2, 'e': 2, 't': 2, 'n': 2, 'c': 2, 's': 2, 'I': 1, 'v': 1, 'p': 1, 'y': 1, 'h': 1, 'u': 1, 'r': 1, 'a': 1})
    Counter({'I': 1, 'love': 1, 'python': 1, 'counter': 1, 'class': 1})
    Counter({'what': 'python', 'action': 'love', 'who': 'I'})
    Counter({'what': 'python', 'action': 'love', 'who': 'I'})
    

2. Python Counter Class Functions Example.

  1. In fact, the python Counter class inherits the python dit class, so it can call the methods supported by python dict class. In addition, Counter also provides the following three commonly used methods.
  2. elements(): This method returns an iterator of all the elements contained in the Counter.
  3. most_common(n): This method returns the first n elements that appear most frequently in Counter.
  4. subtract([iterable-or-mapping]): This method calculates the subtraction of two Counter objects. In fact, it calculates the number of occurrences of each element after subtraction.
  5. Below are some python Counter class method usage example, you can read the comments for detailed learning.
    from collections import Counter
        
    def counter_method_exmple():
        
        print("# create a new Counter object c.")
        c = Counter()
        print(c)
        
        print()
        print("# because the counter object does not contains the key 'python', so the c['python'] value should be 0.")
        print("c['python']")
        print(c['python'])
        
        print()
        print("# loop in the string array, record each string occurrence count number.")
        str_arr = ['python', 'java', 'C', 'C++', 'JavaScript', 'python']
        print('str_arr = ', str_arr)
        for str in str_arr:
            
            c[str] += 1
            
        print(c)    
        
        print()
        print('# list all the counter object key elements with the counter object elements() function.')
        c_l = list(c.elements())
        print(c_l)
        
        print()
        print('# Convert a string to python counter object.')
        c_chr = Counter('I love pythoooon')
        print(c_chr)
        
        print()
        print('# Gets the first three letters with the most occurrences')
        print(c_chr.most_common(3))
        
        print()
        print('Call the counter object subtract function.')
        c_1 = Counter(a=6, b=3, c=5, d=10)
        print('c_1', c_1)
        c_2 = Counter(a=1, b=1, c=6, d=9)
        print('c_2', c_2)
        c_1 = c_1.subtract(c_2)
        print('c_1.subtract(c_2)', c_1)
        
        print()
        print('# use del command to remove the key-value pair in the python counter object.')
        c_3 = Counter({'a':2, 'b':6, 'c':-9})
        print(c_3)
        del c_3['c']
        print(c_3)
        
        print()
        print('# Get all the elements values in the Counter object.')
        c_4 = Counter(java=1, python=2, c=3, javascript=4, swift=5)
        print('c_4 = ', c_4)
        print('c_4_values = ', c_4.values())
        sum_c_4_values = sum(c_4.values())
        print('sum(c_4.values()) = ', sum_c_4_values)
        
        print()
        print('# Convert Counter object to a list object and only reserve the keys.')
        print('c_4 = ', c_4)
        c_4_l = list(c_4)
        print('list(c_4) = ', c_4_l)
        
        print()
        print('# Convert Counter object to a set object and only reserve the keys.')
        print('c_4 = ', c_4)
        c_4_s = set(c_4)
        print('set(c_4) = ', c_4_s)
        
        print()
        print('# Convert Counter object to a dict object and only reserve the keys.')
        c_4_dict = dict(c_4)
        print('dict(c_4) = ', c_4_dict)
        
        print()
        print('# c.items() method return a list object that contain the key item and the key item occurrence counts.')
        counter_items = c_4.items()
        print('c_4.items() = ', counter_items)
        
        print()
        print('# convert the above counter_items to a Counter object again.')
        c_5 = Counter(dict(counter_items))
        print(c_5)
        
        print()
        print('# Get the three elements with the least number of occurrences')
        print('c_5.most_common()[:-4:-1] = ', c_5.most_common()[:-4:-1])
        
        print()
        print('# clear the counter object key-value pairs.')
        c_5.clear()
        print('c_5.clear() = ', c_5)
        
        print()
        print("# operate counter object with plus, minus function.")
        c_6 = Counter(x=1, y=3, z=5)
        print('c_6 = ', c_6)
        c_7 = Counter(x=2, y=4, z=6)
        print('c_7 = ', c_7)
        print('c_6 + c_7 = ', c_6 + c_7)
        print('c_6 - c_7 = ', c_6 - c_7)
        print('c_6 & c_7 = ', c_6 & c_7)
        print('c_6 | c_7 = ', c_6 | c_7)
        print('+c_6 = ', +c_6)
        print('-c_7 = ', -c_7)
    
    if __name__ == '__main__':
        
        counter_method_exmple()
  6. When you run the above python source code, you can get the below output.
    # create a new Counter object c.
    Counter()
    
    # because the counter object does not contains the key 'python', so the c['python'] value should be 0.
    c['python']
    0
    
    # loop in the string array, record each string occurrence count number.
    str_arr =  ['python', 'java', 'C', 'C++', 'JavaScript', 'python']
    Counter({'python': 2, 'java': 1, 'C': 1, 'C++': 1, 'JavaScript': 1})
    
    # list all the counter object key elements with the counter object elements() function.
    ['python', 'python', 'java', 'C', 'C++', 'JavaScript']
    
    # Convert a string to python counter object.
    Counter({'o': 5, ' ': 2, 'I': 1, 'l': 1, 'v': 1, 'e': 1, 'p': 1, 'y': 1, 't': 1, 'h': 1, 'n': 1})
    
    # Gets the first three letters with the most occurrences
    [('o', 5), (' ', 2), ('I', 1)]
    
    Call the counter object subtract function.
    c_1 Counter({'d': 10, 'a': 6, 'c': 5, 'b': 3})
    c_2 Counter({'d': 9, 'c': 6, 'a': 1, 'b': 1})
    c_1.subtract(c_2) None
    
    # use del command to remove the key-value pair in the python counter object.
    Counter({'b': 6, 'a': 2, 'c': -9})
    Counter({'b': 6, 'a': 2})
    
    # Get all the elements values in the Counter object.
    c_4 =  Counter({'swift': 5, 'javascript': 4, 'c': 3, 'python': 2, 'java': 1})
    c_4_values =  dict_values([1, 2, 3, 4, 5])
    sum(c_4.values()) =  15
    
    # Convert Counter object to a list object and only reserve the keys.
    c_4 =  Counter({'swift': 5, 'javascript': 4, 'c': 3, 'python': 2, 'java': 1})
    list(c_4) =  ['java', 'python', 'c', 'javascript', 'swift']
    
    # Convert Counter object to a set object and only reserve the keys.
    c_4 =  Counter({'swift': 5, 'javascript': 4, 'c': 3, 'python': 2, 'java': 1})
    set(c_4) =  {'javascript', 'python', 'swift', 'c', 'java'}
    
    # Convert Counter object to a dict object and only reserve the keys.
    dict(c_4) =  {'java': 1, 'python': 2, 'c': 3, 'javascript': 4, 'swift': 5}
    
    # c.items() method return a list object that contain the key item and the key item occurrence counts.
    c_4.items() =  dict_items([('java', 1), ('python', 2), ('c', 3), ('javascript', 4), ('swift', 5)])
    
    # convert the above counter_items to a Counter object again.
    Counter({'swift': 5, 'javascript': 4, 'c': 3, 'python': 2, 'java': 1})
    
    # Get the three elements with the least number of occurrences
    c_5.most_common()[:-4:-1] =  [('java', 1), ('python', 2), ('c', 3)]
    
    # clear the counter object key-value pairs.
    c_5.clear() =  Counter()
    
    # operate counter object with plus, minus function.
    c_6 =  Counter({'z': 5, 'y': 3, 'x': 1})
    c_7 =  Counter({'z': 6, 'y': 4, 'x': 2})
    c_6 + c_7 =  Counter({'z': 11, 'y': 7, 'x': 3})
    c_6 - c_7 =  Counter()
    c_6 & c_7 =  Counter({'z': 5, 'y': 3, 'x': 1})
    c_6 | c_7 =  Counter({'z': 6, 'y': 4, 'x': 2})
    +c_6 =  Counter({'z': 5, 'y': 3, 'x': 1})
    -c_7 =  Counter()
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x