Is Python Smart Enough to do Sorting like this?

Stephen Horne steve at ninereeds.fsnet.co.uk
Fri Mar 12 23:03:30 EST 2004


On Sat, 13 Mar 2004 01:26:25 +0000, "shalendra chhabra"
<shalen_itbhu at hotmail.com> wrote:

>Is it possible to order this itemset in an increasing order of key: value 
>with respect to keys. For example: if
>key4>key2>key3>key1
>then the resulting ordering should be in such a way:
>
>key4:value4, key2: value2,key3:value3>key1: value1

What you seem to be describing is decreasing order of key - the
highest key value (key4) first, with progressively smaller values at
later positions.

This is not hard. The only minor annoyance is that, unlike for
instance a C++ map, Python dictionaries don't naturally iterate in
sorted order (they use hashing rather than a tree structure, which
overall is probably neither better nor worse - just different).

Sorting tasks are quite common, so while that are not exactly
difficult I imagine there's a good guide on the internet somewhere for
newbies (links anyone?).

In this case, once you have the dictionary of key:value pairs you
extract a list of keys and sort it appropriately. The default sort is
in increasing order, so you reverse that to get decreasing order.
Then, if necessary, you use a list comprehension to get a list of
(key, value) tuples in the needed order. The list comprehension is
often redundant, though, as you can normally just iterate the sorted
keys and read the values from the dictionary when they're needed.

Here is a quick function...

def pairs_by_decreasing_key (p_Dict) :
  """
  Takes a dictionary and derives a list of (key, value) tuples
  in decreasing order of key.
  """
  tmp = p_Dict.keys (); tmp.sort (); tmp.reverse ()

  return [(i, p_Dict [i]) for i in tmp]


-- 
Steve Horne

steve at ninereeds dot fsnet dot co dot uk



More information about the Python-list mailing list