Arijit Ghosh
Arijit Ghosh

Reputation: 151

Frequency count in a dictionary -- Python using comprehension

I have a dictionary and would like to count the frequency using Python comprehension.

Example:

Input

{0: 'Succeeded', 1: 'Succeeded', 2: 'Failed', 3: 'Failed', 4: 'Succeeded'}

Output

{'Succeeded':3,'Failed':2}

Upvotes: 1

Views: 4112

Answers (1)

timgeb
timgeb

Reputation: 78650

Instead of using a comprehension, just apply a Counter to the values of your dictionary.

>>> from collections import Counter
>>> d = {0: 'Succeeded', 1: 'Succeeded', 2: 'Failed', 3: 'Failed', 4: 'Succeeded'}
>>> Counter(d.values())
Counter({'Failed': 2, 'Succeeded': 3})

General Tip

Dictionaries with consecutive integer keys are a waste of memory. You could just use a list

my_list = ['Succeeded', 'Succeeded', 'Failed', 'Failed', 'Succeeded']

into which you can index with integers 0, 1, 2, ... like you would with your original dictionary. The list takes less memory and values can be found without hashing keys.

In this case, Counter(my_list) would construct the dictionary you desire.


WARNING BAD CODE BELOW

You could but not should write a comprehension as follows

>>> vals = list(d.values())
>>> {v:vals.count(v) for v in vals}
{'Failed': 2, 'Succeeded': 3}

but I strongly advise against using this comprehension because as opposed to the O(n) Counter solution, it has quadratic time complexity. For each value in vals, vals is iterated in order to count the value.

Upvotes: 6

Related Questions