Sorting a Python Dictionary

December 19, 2009

Dictionaries in python are unordered. What you can do is get the keys, sort them, and then produce a new dictionary in the order you want.

lYearNumbers = lYears.items()
lYearNumbers.sort()
lYearNumbers.reverse()
lYears = [value for key, value in lYearNumbers]

This code gets the keys from the lYears dictionary, sorts it, reverses it (so the current year is at the top of the list), then replaces lYears with the dictionary in the order requested.

Simpler

Here's a simpler example that doesn't use a list comprehension. The first line here represents how the lHistory dictionary is first created. This code will be run once for each entry in the dictionary.

lHistory[int(lRevision)] = ({'revision' : lRevision, 'changeset':lChangeSet, 'user':lUser, 'date':lDate, 'comment':lSummary})

lRevisions = lHistory.keys()
lRevisions.sort()
lRevisions.reverse()
lReturn = []
for revision in lRevisions:
    lReturn.append(lHistory[revision])
return lReturn

Note that this returns a list, not a dictionary.

Decorated Sort

Here's another alternate way of doing things. This involves coercing the data structure you have into a tuple, sorting on that tuple and then producing the structure you want from that.

lBandTotals = {}
for band_slug in lBandResults.keys():
    lBandResults[band_slug] = sorted(lBandResults[band_slug])[:6]
    lTotalPoints = sum(lBandResults[band_slug])
    lBandTotals[band_slug] = lTotalPoints

At this point we have a dictionary with a slug as a key, and the total number of points from the top 6 contests as the value.

lDecoratedList = [(points, slug) for slug, points in lBandTotals.items()]

lDecoratedList is a list of tuples, where each tuple is points and then slug.

lDecoratedList.sort()

Sort on this list sorts it by the tuples - it sorts by points first and then by the slug

lSortedResults = [{'slug':slug, 'points':points} for points, slug in lDecoratedList]
lPosition = 1
for row in lSortedResults:
    row['band'] = lBands[row['slug']] 
    row['position'] = lPosition
    lPosition += 1

Finally, we produce a list of dictionaries. This list is in the sorted order, each dictionary now contains the slug, the number of points, the band name and the position in the list.