# [Tutor] [tutor] dictionary

Kent Johnson kent37 at tds.net
Wed Jun 7 11:56:50 CEST 2006

```emilia12 at mail.bg wrote:
> how can i print a dictionary, sorted by the values?

A dictionary itself is an unordered collection and can't be sorted. But
you can sort and print the list of key, value pairs returned by
dict.items(). For example:

In [3]: from operator import itemgetter

In [4]: d = { 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four' }

In [5]: for k, v in sorted(d.items(), key=itemgetter(1)):
...:     print k, '=', v
...:
...:
4 = four
1 = one
3 = three
2 = two

d.items() returns a list of (key, value) pairs:
In [6]: d.items()
Out[6]: [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]

itemgetter(1) actually returns a function which, when called with an
argument x, returns x[1]:
In [7]: get1 = itemgetter(1)

In [8]: get1(d.items())
Out[8]: (2, 'two')

In [9]: get1('abc')
Out[9]: 'b'

Using itemgetter(1) as the key argument to sorted() makes the sort
happen on the second item of each pair, the value.

(This example requires Python 2.4; Python 2.3 has no sorted() function,
you have to do the sort in a separate step using list.sort(). In earlier
Python you have to use a different trick called DSU to sort by key.)

Kent

```