dictionary: sorting the values preserving the order

Ron_Adam radam2 at tampabay.rr.com
Fri Apr 1 03:57:45 EST 2005


On 31 Mar 2005 22:40:53 -0800, "Rakesh" <rakesh_usenet at yahoo.com>
wrote:

>Hi,
>  For a particular problem of mine, I want to sort <key, value> pairs
>by its value.
>
>Eg:
>
>Input:
>
>A, 4
>B, 5
>C, 1
>D, 2
>E, 3
>
>I would like the output to be:
>
>C
>D
>E
>A
>B
>
>i.e. I would like to get the keys in the sorted order of values.

Generally, dictionaries nearly always have two parts. The dictionary
itself, and a separate list of keys to access it with.  

To access the dictionary in a particular order, you just need a sorted
key list.

Since what you want is to access by value, you need to create a second
dictionary with the values as the keys.  That will only work if the
values never repeat. If they do, then you need to use a list and not a
dictionary.

This creates a second dictionary with a sorted value key list.

alpha_dict = {'A':4, 'B':5, 'C':1, 'D':2, 'E':3}

# Create a new dictionary with keys and values exchanged.
num_dict = {}
for k in alpha_dict.keys():
    num_dict[ alpha_dict[k] ] = k

# Get the num_dict keys and sort them.
num_keys = num_dict.keys()
num_keys.sort()


Ron




More information about the Python-list mailing list