3

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.

Jay Patel
  • 137
  • 7

2 Answers2

8

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})
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
  • 2
    If you are lazy, you can also pass `'dslew'` because strings are iterable. – jpp Nov 11 '18 at 02:14
  • @JayPatel Glad I could help! If my answer helped to solve your problem, please consider [marking it as accepted](http://meta.stackexchange.com/a/5235/195035). That's the customary way of indicating that your question is "resolved" and thanking the person who helped you. – Dani Mesejo Nov 11 '18 at 02:20
0

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}
Charles Landau
  • 4,187
  • 1
  • 8
  • 24