Sort the values of a dict

mattia gervaz at gmail.com
Fri Dec 18 17:34:53 EST 2009


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



More information about the Python-list mailing list