Q: listsort and dictsort - official equivalents?

Neville D NevilleD.python at sgr-a.net
Tue Jun 19 21:22:24 EDT 2007


I expressed my creativity & created two routines, listsort & dictsort.  

def listsort(l,cmp=None): l.sort(cmp); return l
def dictsort(d,cmp=None):return [(k,d[k])for k in listsort(d.keys(),cmp=cmp)]

Basically I am more familiar with sorting inside a for loop, eg in
bourne shell one can do "for loop sorts": 

for group in $(sort /etc/group); do 
  echo group; 
done

In python I must kick off a sort on the line before I start the
iteration.  (This does make sense because at the end of the day the sort
has complete BEFORE the for loop can proceed - that is... until the day
when python lists have a secondary index ;-).

group_list=group_dict.keys()
group_list.sort()
for group in group_list: # do
  print group,group_dict[group]
# done

I am sure python has a more concise way of doing this, any hints?

Cheers
NevilleD

# examples:

#!/usr/bin/env python
## -*- coding: utf-8 -*-
## purpose: demo sorting in python
def aleph_cmp(a,b): # class only needs the "<" operator
  if a<b: return -1
  elif b<a: return 1
  else: return 0 # fi
# end aleph_cmp

def listsort(l,cmp=None): l.sort(cmp); return l # end

# example application:
mydict=dict(zip("cba",(2,1,3)))

print "a) sort by the first key using the std cmp"
for key in listsort(mydict.keys(),cmp=cmp): # do
  print key,mydict[key]
# od

# if your object had a '-' operator, then you would not need to do this.
print "b) custom sort by the first key - need the '<' operator"
for key in listsort(mydict.keys(),aleph_cmp): # do
  print key,mydict[key]
# od

print "c) custom sort by the second key - using the numeric '-' operator"
for key in listsort(mydict.keys(),cmp=lambda a,b: mydict[a]-mydict[b]): # do
  print key,mydict[key]
# od

# ᚠinally: I ᛒelieve listsort & dictsort aᚱe not in the ᛋtd... ᛒut ᛗayᛒ they ᚱ?
def dictsort(d,cmp=None):return [(k,d[k])for k in listsort(d.keys(),cmp=cmp)] # end

print "d) 'dictsort' sort by the second key - using the numeric '-' operator"
for key,val in dictsort(mydict,cmp=lambda a,b: mydict[a]-mydict[b]): # do
  print key,val
# od

Am I missing some obvious standard routine?
-- 
Neville D - NZ 
᛭ᚾᛖ᛬​ᚡᛁᛚᛖ᛬​ᚡᛖᛚᛁᛋ᛭ᛖᛚᚪᛏᚢᛗ᛬​ᚪ᛬​ᛎᛖᚢᛋ᛬​ᚾᚰ᛬​ᛞᛖᛈᚱᛁᛗᚪᛏ᛭
note: This document contains Anglo-Saxon Futhorci UTF-8 characters 
from: http://junicode.sourceforge.net/ - eg ᚦᛖ  ᚠᛁᚱᛋᛏ  ᚠᚰᛏ




More information about the Python-list mailing list