On Fri, Dec 18, 2009 at 5: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 > I won't engage in any arguments about pythonicity but it seems simpler if you convert to a list of tuples right away.
d = {1:('a', 1, 12), 5:('r',21,10), 2:('u',9,8)} l = [(x, d[x]) for x in d.keys()] def third(q): return q[1][2] s = sorted(l, key=third) print s -- http://mail.python.org/mailman/listinfo/python-list