1

When doing practice problems, I often times need to build a dict with keys as elements from an array and values as frequencies in which they appear. I usually do something like:

charFreqs = {}
for c in myStr:
      if c in charFreqs:
           charFreqs[c] += 1
      else:
           charFreqs[c] = 1

This works fine, but I am wondering if there is a more concise method. It seems like a lot of code to accomplish a pretty simple and common task.

Matt
  • 478
  • 4
  • 14
  • 3
    Yes, [`collections.Counter`](https://docs.python.org/3/library/collections.html#collections.Counter). Simply do `charFreqs = Counter(myStr)` – smci Jan 14 '21 at 22:34
  • 1
    Duplicate of [How can I count the occurrences of a list item?](https://stackoverflow.com/a/5829377/202229). Look at the solution using `Counter`, not the accepted solution with `list.count()` – smci Jan 14 '21 at 22:36

1 Answers1

1

I like using a defaultdict for this sort of thing.

import collections
charFreqs = collections.defaultdict(int)
for c in myStr:
    charFreqs[c] += 1
Robin Davis
  • 622
  • 4
  • 10