Connecting Tech Pros Worldwide Forums | Help | Site Map

Sort dictionary by values (complex)!

kdt kdt is offline
Member
 
Join Date: Mar 2007
Posts: 50
#1: Aug 18 '07
Hi,

I need to perform some horrible functions in python I need to do, using sort in a similar way that Excel can.

With a dictionary like:
Expand|Select|Wrap|Line Numbers
  1. >>> d
  2. {8: (99, 99), 9: [(55, 67), (77, 66), (67, 88)], 4: [(45, 78), (56, 78), (99, 78)], 5: (67, 77)}
  3.  
I want to sort the entire dictionary based on the last values in each line. First for [-1][0] and then[-1][0].

So sorted descending I would like the output to look like:
Expand|Select|Wrap|Line Numbers
  1. >>> d
  2. {8: (99, 99), 4: [(45, 78), (56, 78), (99, 78)], 9: [(55, 67), (77, 66), (67, 88)], 5: (67, 77)}
  3.  
Many thanks

kdt kdt is offline
Member
 
Join Date: Mar 2007
Posts: 50
#2: Aug 19 '07

re: Sort dictionary by values (complex)!


Got a response for this from the python mailing list. Just thought I should share it with you all here.

Quote:
import operator
cmplast = lambda x, y: cmp(x[-1], y[-1])
sorted(d.items(), key=operator.itemgetter(1), cmp=cmplast, reverse=True)

or

cmplast1 = lambda x, y: cmp(x[1][-1], y[1][-1])
sorted(d.items(), cmp=cmplast1, reverse=True)

[(8, [(99, 99)]), (4, [(45, 78), (56, 78), (99, 78)]), (9, [(55, 67),
(77, 66), (67, 88)]), (5, [(67, 77)])]
Thanks Sanchez!
bartonc's Avatar
Moderator
 
Join Date: Sep 2006
Location: Minden, Nevada, USA
Posts: 6,400
#3: Aug 20 '07

re: Sort dictionary by values (complex)!


Quote:

Originally Posted by kdt

Got a response for this from the python mailing list. Just thought I should share it with you all here.



Thanks Sanchez!

Thanks for keeping us apprised!
Reply