Search code examples
pythonpython-3.xdictionaryinheritancepython-collections

How to access internal dictionary of collection.Counter to extend the functionality of Child class by using Inheritance?


I want to add 2 functions in collections.Counter to add functionality to it for sorting and returning minimum n values. For this to work, I need to access the internal dictionary and I don't know how to use it. I checked the internal variables for the class created by using vars(Counter) and also the dunder and other function using dir(Counter). As the dictonary us returned after creating the class so the method and variable is in the constructor itself. So to see the functionality I used dir(Counter.__init__) but could not find something good to use, as only methods were there.

For example if I do counter = Counter(iterable), i need to access that self.counter variable Inside the class itself but I do not which variable that would be.

Below is the code I want to implement

from collections import Counter
import heapq
from operator import itemgetter


class CounterNew(Counter):
    '''
    Increase the functionality of collections.Counter() class
    '''
    def least_common(n:int)->list:
        '''
        Get the least common elements
        args:
            n: How many elements you want to have which have the lowest frequency
        out: list of tuples as [(key,frequency)]
        '''
        return heapq.nsmallest(n, counter.items(), key=lambda x:x[1])
    
    
    def sort_by_freq(self,reverse:bool=False)->dict:
        '''
        Sort the Dictonary by frequency counts
        args:
            reverse: Whether to sort the dictonary in increasing or decreasing order
        out: Sorted dictonary
        '''
        self.sorted = sorted(counter.items(), key=lambda x:x[1], reverse=reverse) # How can I sort the internal dictonary that is returned by class
        return self.sorted

Solution

  • collections.Counter is a subclass of dict. So it doesn't contain a dictionary in an instance variable, the dictionary is the instance itself. So if you need to access the dictionary, just use self.

    You do the same thing in the sort_by_freq method. Since you want it to return a dict, you need to call dict() to convert it back into a dictionary.

    def least_common(self, n:int)->list:
        return heapq.nsmallest(n, self.items(), key=lambda x:x[1])
    
    def sort_by_freq(self,reverse:bool=False)->dict:
        '''
        Sort the Dictonary by frequency counts
        args:
            reverse: Whether to sort the dictonary in increasing or decreasing order
        out: Sorted dictonary
        '''
        self.sorted = dict(sorted(self.items(), key=lambda x:x[1], reverse=reverse))
        return self.sorted