sorting values in dict

Chris Barker chrishbarker at
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".
    >>> 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))
        pairs = map(None, list_to_sort_by,range(len(list_to_sort_by)))
        out_list = []
        for i in map(lambda x: x[1],pairs):
        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
# it can a little cleaner:

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

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


Christopher Barker,
ChrisHBarker at                 ---           ---           --- ---@@       -----@@       -----@@
                                   ------@@@     ------@@@     ------@@@
Oil Spill Modeling                ------   @    ------   @   ------   @
Water Resources Engineering       -------      ---------     --------    
Coastal and Fluvial Hydrodynamics --------------------------------------

More information about the Python-list mailing list