#!/usr/bin/env python import operator def groupdict(dict, match_func=operator.eq): """Groups similar dictionary values by key >>> groupdict({1: 'a', 3: 'a', 4: 'b', 5: 'c', 6: 'a', 7: 'b', 8: 'a'}) [[1, 3, 6, 8], [4, 7], [5]] """ groups = [] ids = dict.keys() while ids: group = [ids[0]] groups.append(group) val = dict[ids[0]] for id in ids[1:]: if match_func(val, dict[id]): group.append(id) for id in group: ids.remove(id) return groups if __name__ == '__main__': import doctest import sys sys.exit(doctest.testmod().failed)