''' dictionarysorting.py -- examples of sortinng dictionaries by key and value. Jeff Ondich, 30 Jan 2008 ''' print '============= a dictionary, its items, and its keys ===============' theDictionary = {'goat':5, 'zebu':9, 'kudu':9, 'moose':27, 'aardvark':9} print "theDictionary:", theDictionary print "theDictionary.items():", theDictionary.items() print "theDictionary keys():", theDictionary.keys() print print '============= a dictionary\'s keys & values, sorted by key ===============' keys = theDictionary.keys() keys.sort() for key in keys: print key, theDictionary[key] print print '============= a dictionary\'s keys & values, sorted by value ===============' print '============= version 1, using the "sorted" function and ===============' print '============= default comparison function for the values ===============' for key in sorted(theDictionary, key=theDictionary.get, reverse=True): print key, theDictionary[key] print print '============= a dictionary\'s keys & values, sorted by value ===============' print '============= version 2, using a global dictionary and a ================' print '============= custom comparison function ================' def valueCmp(a, b): valueComparison = cmp(theDictionary[b], theDictionary[a]) if valueComparison == 0: return cmp(a, b) else: return valueComparison keys = theDictionary.keys() keys.sort(valueCmp) for key in keys: print key, theDictionary[key] print print '============= a dictionary\'s keys & values, sorted by value ===============' print '============= version 3, using a locally defined custom ===============' print '============= comparison function ===============' def getKeysSortedByValue(theDict): def valCmp(a, b): valueComparison = cmp(theDictionary[b], theDictionary[a]) if valueComparison == 0: return cmp(a, b) else: return valueComparison keys = theDict.keys() keys.sort(valCmp) return keys sortedKeys = getKeysSortedByValue(theDictionary) for key in sortedKeys: print key, theDictionary[key] print print '============= a dictionary\'s keys & values, sorted by value ===============' print '============= version 3, using list comprehensions ===============' items = theDictionary.items() items = [(v, k) for (k, v) in items] items.sort() items.reverse() items = [(k, v) for (v, k) in items] for (k, v) in items: print k, v