Sort the values of a dict

mattia gervaz at gmail.com
Fri Dec 18 17:42:52 EST 2009


Actually, in order to use duplicate values I need something like:

>>> import copy
>>> d = {1:('a', 1, 12), 5:('r', 21, 10), 2:('u', 9, 8), 3:('u', 9, 8) }
>>> dc = copy.deepcopy(d)
>>> 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)
...             del d[k] # speedup and use duplicate values
...             break
...
>>> res = []
>>> for x in pres:
...     res.append((x, dc[x]))
...
>>> res
[(2, ('u', 9, 8)), (3, ('u', 9, 8)), (5, ('r', 21, 10)), (1, ('a', 1, 
12))]
>>>



More information about the Python-list mailing list