Skip to content

Instantly share code, notes, and snippets.

@smith3v
Created August 13, 2012 04:02
Show Gist options
  • Select an option

  • Save smith3v/3336853 to your computer and use it in GitHub Desktop.

Select an option

Save smith3v/3336853 to your computer and use it in GitHub Desktop.

Revisions

  1. smith3v created this gist Aug 13, 2012.
    23 changes: 23 additions & 0 deletions sorting_dict_of_objects.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    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) )