How to make subset of Counter?

2.2k views Asked by At

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.

2

There are 2 answers

2
Dani Mesejo On BEST ANSWER

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})
1
Charles Landau On

You can access each key in c and assign its value to the same key in a new dict.

import collections
c = collections.Counter('achdnsdsdsdsdklaffaefhaew')

def subsetter(c, sub):
  out = {}
  for x in sub:
    out[x] = c[x]
  return collections.Counter(out)

subsetter(c, ["d","s","l","e","w"])

Yields:

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