sorting values in dict

Chris Barker chrishbarker at home.net
Thu Jun 14 19:43:22 EDT 2001


Jeroen Wolff wrote:
> I want to display a dict sorted by value.

This brings up what I think is a serious limitation of the list sort()
method: It doesn't return any information about how the items have been
rearranged, so that you could use it to sort another list the same way.
Nor, for that matter does it allow you to pass in a new sorting order.
Here is what I have come up with instead:

def sort_by_other_list(list_to_sort,list_to_sort_by,sortable = 0):

    """
    sort_by_other_list(list_to_sort,list_to_sort_by, sortable = 0):
    
    returns a list of the elements of "list_to_sort", sorted by the
    elements of "list_to_sort_by".
    
    Example:
    >>> sort_by_other_list(['a,','b','c','d'],[4,1,3,2])
    ['b', 'd', 'c', 'a,']
    
    the list that is being sorted does not have to be sortable If the
    list being sorted is sortable, than you can use the "sortable" flag
    and a more efficient method will be used.
    
    """
    if sortable:
        return map(lambda i: i[1], zip(list_to_sort_by,list_to_sort))
    else:
        pairs = map(None, list_to_sort_by,range(len(list_to_sort_by)))
        pairs.sort()
        out_list = []
        for i in map(lambda x: x[1],pairs):
            out_list.append(list_to_sort[i])
        return out_list

# for your case:
dict = {'a':9,'b':7,'c':8,'d':4,'e':6}

keys = sort_by_other_list(dict.keys(),dict.values(),sortable = 1)
for key in keys:
    print key, dict[key]

# If you want to use idea directly (are keys guaranteed to be
sortable?),
# it can a little cleaner:

stuff = zip(dict.values(),dict.keys())
stuff.sort()
print
for value,key in stuff:
    print key,value



NOTE: is there a way to avoid the "map" to extract the first list again?

-Chris


-- 
Christopher Barker,
Ph.D.                                                           
ChrisHBarker at home.net                 ---           ---           ---
http://members.home.net/barkerlohmann ---@@       -----@@       -----@@
                                   ------@@@     ------@@@     ------@@@
Oil Spill Modeling                ------   @    ------   @   ------   @
Water Resources Engineering       -------      ---------     --------    
Coastal and Fluvial Hydrodynamics --------------------------------------
------------------------------------------------------------------------



More information about the Python-list mailing list