#!/usr/bin/env python import sys entries = {} for line in open(sys.argv[1]): [left, right] = line.split() try: entries[right].append(left) # or use has_key except KeyError: # or e[r] = e.get(r, []) + [l] entries[right] = [left] for (right, lefts) in entries.items(): print "%04d '%s'\titems => %s" % (len(lefts), right,lefts)