# sort dictionary by specific values

Arnau Sanchez arnau at ehas.org
Sat Aug 18 21:18:29 CEST 2007

```dorje tarap escribió:

>    2.
>       {8: (99, 99), 9: [(55, 67), (77, 66), (67, 88)], 4: [(45, 78),
>       (56, 78), (99, 78)], 5: (67, 77)}
>
>
> I want to sort the entire dictionary based on the last values in each
> line. First for [-1][0] and then[-1][0]

Each "line" means each value in the dictionary?

Did you mean ordering [-1][0] and then [-1][1]?

Dictionaries cannot be ordered, but you can work with its items (as a list).

Your data is not homogeneous (values in the dictionary are both tuples
and list of tuples). If you can build it that way:

d = {8: [(99, 99)], 9: [(55, 67), (77, 66), (67, 88)], 4: [(45, 78),
(56, 78), (99, 78)], 5: [(67, 77)]

It would be easy to sort:

import operator
cmplast = lambda x, y: cmp(x[-1], y[-1])
sorted(d.items(), key=operator.itemgetter(1), cmp=cmplast, reverse=True)

or

cmplast1 = lambda x, y: cmp(x[1][-1], y[1][-1])
sorted(d.items(), cmp=cmplast1, reverse=True)

[(8, [(99, 99)]), (4, [(45, 78), (56, 78), (99, 78)]), (9, [(55, 67),
(77, 66), (67, 88)]), (5, [(67, 77)])]

```