sorting values in dict

Bengt Richter bokr at accessone.com
Sat Jun 16 03:22:38 CEST 2001


On Fri, 15 Jun 2001 12:33:50 +0200, "Alex Martelli"
<aleaxit at yahoo.com> wrote:

>"Victor Muslin" <victor at prodigy.net> wrote in message
>news:3b292d23.1831931958 at localhost...
>> This may not be the shortest or most efficient, but it does the trick:
>>
>> a={'a':9,'b':8,'c':7}
>> l=[]
>> for k,v in a.items():
>>   l.append((v,k))
>> l.sort()
>> for v,k in l:
>>   print v,k
>
>I think it's pretty close, except that, to build l,
>    l = [(v,k) for k,v in a.items()]
>may be (very slightly) shorter and more efficient.
>
Nobody seems to be doing it my way:
--
def sortedItemsOfDir(d,dir='a'):	#'d'escending else default
	if dir=='d':
		def cmpi(x,y):	#descending
			if x[1]>y[1]: return -1
			if x[1]<y[1]: return 1
			return 0
	else:
		def cmpi(x,y):	#descending
			if x[1]>y[1]: return 1
			if x[1]<y[1]: return -1
			return 0
	items = d.items()
	items.sort(cmpi)
	return items

 >>> from sortdir import sortedItemsOfDir
 >>> d={'a':5,'b':2,'c':3,'d':1}
 >>> sortedItemsOfDir(d)
 [('d', 1), ('b', 2), ('c', 3), ('a', 5)]
 >>> sortedItemsOfDir(d,'d')
 [('a', 5), ('c', 3), ('b', 2), ('d', 1)]
 >>> for k,v in sortedItemsOfDir(d): print k,v
 ...
 d 1
 b 2
 c 3
 a 5
 >>> for k,v in sortedItemsOfDir(d,'d'): print k,v
 ...
 a 5
 c 3
 b 2
 d 1




More information about the Python-list mailing list