Search code examples
pythondata-structurespython-collections

How to make subset of Counter?


I am experimenting with Python standard library Collections.

I have a Counter of things as

>>> c = Counter('achdnsdsdsdsdklaffaefhaew')
>>> c
Counter({'a': 4,
         'c': 1,
         'h': 2,
         'd': 5,
         'n': 1,
         's': 4,
         'k': 1,
         'l': 1,
         'f': 3,
         'e': 2,
         'w': 1})

What I want now is to somehow get subset of this counter as another Counter object. Just like this:

>>> new_c = do_subset(c, [d,s,l,e,w])
>>> new_c
Counter({'d': 5,
         's': 4,
         'l': 1,
         'e': 2,
         'w': 1})

Thank you in advance.


Solution

  • You could simply build a dictionary and pass it to Counter:

    from collections import Counter
    
    c = Counter({'a': 4,
                 'c': 1,
                 'h': 2,
                 'd': 5,
                 'n': 1,
                 's': 4,
                 'k': 1,
                 'l': 1,
                 'f': 3,
                 'e': 2,
                 'w': 1})
    
    
    def do_subset(counter, lst):
        return Counter({k: counter.get(k, 0) for k in lst})
    
    
    result = do_subset(c, ['d', 's', 'l', 'e', 'w'])
    
    print(result)
    

    Output

    Counter({'d': 5, 's': 4, 'e': 2, 'l': 1, 'w': 1})