0

I have a function which takes an array of items and returns a dictionary. The keys of the returned dictionary are the original items of the array, and the values are the number of times those items appeared in the original array.

For example:

[2, 2, 3] --> {2: 2, 3: 1}

I wrote the following:

compress_dupes(array):
    out = {}

    for i in array:
        if i in out:
            out[i] = out[i] + 1
        else:
            out[i] = 1

    return out

This works. But I want to make it a little more elegant. Is there a more "pythonic" way of doing this, with comprehensions or any other way?

JavascriptLoser
  • 1,853
  • 5
  • 34
  • 61

1 Answers1

2

Use collections.Counter()

from collections import Counter

c = Counter(iterable)
Primusa
  • 13,136
  • 3
  • 33
  • 53