A functional task, I am sure

Now that I dove into functional programming (only using dojo and python, but it’s a start) and feel that my brain has not completely made the switch yet, I come across problems that look like they are best to be solved with functional programming. Isn’t it always that way, when you have started something new and are still excited about it, that the every day problems seem that they want to be solved the new way? Anyway, here it goes.

I got this dictionary. The keys are IDs and the values are kind of a rank. Now I want to sort the IDs by their rank.
I am sure there is a simple one liner for that. But I didn’t come up with it yet.
I only came up with a quite dumb concat, sort and split solution. Not elegant at all.


d = {4: 6, 12: 4, 14: 14, 18: 16, 32: 6,
    33: 24, 40: 27, 41: 6, 44: 25, 106: 2}
d1 = ["%06d" % v+'_'+str(k) for k,v in d.items()]
# d1 is now something like this:
# ['000006_4', '000004_12', '000014_14', '000016_18', ...]
d1.sort() # That allows us to sort, which does it
sorted = [int(i.split("_")[1]) for i in d1 ]

This has several drawbacks, but it was as good as I got :-(.
I hope this has no negative effect on my career.

[Update] Thanks to Daniel’s second post, this is the solution!


sorted(d.items(), key=itemgetter(1))

Awesome, thanks!

5 Comments »

  1. Daniel Lange said,

    February 19, 2008 at 6:13 pm

    Does this help?
    http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52306

  2. Daniel Lange said,

    February 19, 2008 at 6:18 pm

    Or this (Python 2.4+)?
    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/304440

  3. Bär said,

    February 19, 2008 at 6:35 pm

    You use the decorate-sort-undecorate pattern.
    http://wiki.python.org/moin/HowTo/Sorting.

  4. Alex Martelli said,

    February 21, 2008 at 12:41 am

    Actually, your 1-liner is returning key-value pairs (sorted by value), not just keys sorted by values (IDs sorted by rank, in your case); for the latter task, there’s an even simpler and more elegant 1-liner:

    sorted(d, key=d.get)

    The key= feature of sort/sorted internally does DSU at high speed and with maximal precision (it will never compare ANYTHING but the specified sorting key; items with identical sorting keys remain in the same order as they were in the input), so there’s little need nowadays to delve into implementing DSU by hand (and I say that happily, even though years ago my articles, posts and books were instrumental in popularizing DSU;-).

    Alex

  5. Wolfram said,

    February 21, 2008 at 10:47 am

    thank you alex!
    just for those like me, who didnt know DSU=”decorate-sort-undecorate”, as Bär mentioned …
    and btw i just found http://www.strayneuron.com/blog/archives/298 solving the same problem, glad i am not alone :-)

    thx all

RSS feed for comments on this post · TrackBack URL

Leave a Comment