Skip to content

Instantly share code, notes, and snippets.

@smith3v
Created August 13, 2012 04:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smith3v/3336853 to your computer and use it in GitHub Desktop.
Save smith3v/3336853 to your computer and use it in GitHub Desktop.
Sorting a dict by property of the stored object
stats = Dict()
class Stats:
""" A class to keep some stats """
def __init__(self):
self.prop1 = 0
self.prop2 = 0
# Filling the dict with objects
for key in stats_data.iterkeys():
stat_item = get_stats_item(key)
if not stat_item in stats:
stats[ stat_item ] = Stats()
stats[ stat_item ].prop1 = get_prop1()
stats[ stat_item ].prop2 = get_prop2()
# The sorting itself
sorted_stats = sorted(stats.iteritems(), key=lambda (k,v): v.prop2, reverse=True)
# Accessing the sorted results
for item in sorted_stats:
print( str(item[0]) + "\t" + str(item[1].prop1) + "\t" + str(item[1].prop2) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment