Borrowing the source of collections.Counter.most_common
and inverting as appropriate:
from operator import itemgetter
import heapq
import collections
def least_common_values(array, to_find=None):
counter = collections.Counter(array)
if to_find is None:
return sorted(counter.items(), key=itemgetter(1), reverse=False)
return heapq.nsmallest(to_find, counter.items(), key=itemgetter(1))
>>> data = [1,1,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4,4,4,4]
>>> least_common_values(data, 2)
[(1, 2), (2, 4)]
>>> least_common_values([1,1,2,3,3])
[(2, 1), (1, 2), (3, 2)]
>>>