## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

# 5.4. Sorting Keys or Indices Basedon the Corresponding Values

Credit: John Jensen, Fred Bremmer, Nick Coghlan

## Problem

You need to count the occurrences of various items and present the items in order of their number of occurrences—for example, to produce a histogram.

## Solution

A histogram, apart from graphical issues, is based on counting the occurrences of items (easy to do with a Python list or dictionary) and then sorting the keys or indices in an order based on corresponding values. Here is a subclass of `dict` that adds two methods for the purpose:

```class hist(dict):
''' add 'increment' to the entry for 'item' '''
self[item] = increment + self.get(item, 0)
def counts(self, reverse=False):
''' return list of keys sorted by corresponding values '''
aux = [ (self[k], k) for k in self ]
aux.sort( )
if reverse: aux.reverse( )
return [k for v, k in aux]```

If the items you're counting are best modeled by small integers in a compact range, so that you want to keep item counts in a list, the solution is quite similar:

`class hist1(list): def _ _init_ _(self, n): ''' initialize this list to count occurrences of n distinct items ''' list._ _init_ _(self, n*[0]) def add(self, item, increment=1): ''' add 'increment' to the entry for 'item' ''' self[item] += increment def counts(self, reverse=False): ''' return list of indices sorted by corresponding values ''' aux = [ (v, k) for k, v in enumerate(self) ] aux.sort( ) if reverse: aux.reverse( ) return [k for v, k in aux] ...`

## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

No credit card required