I'd write it as: s = sorted(d.iteritems(), key=lambda i: i[1][2]) If using python 3, it should be d.items() instead of d.iteritems().
d.iteritems() is a generator yielding tuples of (key, value) from the dictionary 'd'. lambda i: i[1][2] is the same as: def sort_(i): return i[1][2] but in-line. Chris On Fri, Dec 18, 2009 at 2:34 PM, mattia <ger...@gmail.com> wrote: > Hi all, I have a dictionary that uses dates and a tuples ad key, value > pairs. I need to sort the values of the dict and insert everything in a > tuple. The additional problem is that I need to sort the values looking > at the i-th element of the list. I'm not that good at python (v3.1), but > this is my solution: > > >>> d = {1:('a', 1, 12), 5:('r', 21, 10), 2:('u', 9, 8)} > >>> t = [x for x in d.values()] > >>> def third(mls): > ... return mls[2] > ... > >>> s = sorted(t, key=third) > >>> pres = [] > >>> for x in s: > ... for k in d.keys(): > ... if d[k] == x: > ... pres.append(k) > ... break > ... > >>> res = [] > >>> for x in pres: > ... res.append((x, d[x])) > ... > >>> res > [(2, ('u', 9, 8)), (5, ('r', 21, 10)), (1, ('a', 1, 12))] > >>> > > Can you provide me a much pythonic solution (with comments if possible, > so I can actually learn something)? > > Thanks, Mattia > -- > http://mail.python.org/mailman/listinfo/python-list >
-- http://mail.python.org/mailman/listinfo/python-list