Created
August 13, 2012 04:02
-
-
Save smith3v/3336853 to your computer and use it in GitHub Desktop.
Sorting a dict by property of the stored object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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