472,101 Members | 1,503 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,101 software developers and data experts.

Sort dictionary by values (complex)!

50
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
Aug 18 '07 #1
2 2744
kdt
50
Got a response for this from the python mailing list. Just thought I should share it with you all here.

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!
Aug 19 '07 #2
bartonc
6,596 Expert 4TB
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!
Aug 20 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

26 posts views Thread by Weiguang Shi | last post: by
4 posts views Thread by brianobush | last post: by
1 post views Thread by john wright | last post: by
6 posts views Thread by max sharma | last post: by
10 posts views Thread by Ben | last post: by
18 posts views Thread by Marko.Cain.23 | last post: by
5 posts views Thread by jeremit0 | last post: by
8 posts views Thread by Bob Altman | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.