Dictionaries and tuples

Dictionaries have a method called items that returns a list of tuples, where each tuple is a key-value pair.ย 

>>> d = {'a':10, 'b':1, 'c':22}
>>> t = d.items()
>>> print t
[('a', 10), ('c', 22), ('b', 1)]

As you should expect from a dictionary, the items are in no particular order.

However, since the list of tuples is a list, and tuples are comparable, we can now sort the list of tuples. Converting a dictionary to a list of tuples is a way for us to output the contents of a dictionary sorted by key:

>>> d = {'a':10, 'b':1, 'c':22}
>>> t = d.items()
>>> t
[('a', 10), ('c', 22), ('b', 1)]
>>> t.sort()
>>> t
[('a', 10), ('b', 1), ('c', 22)]

The new list is sorted in ascending alphabetical order by the key value.

Multiple assignment with dictionaries

Combining items, tuple assignment and for, you can see a nice code pattern for traversing the keys and values of a dictionary in a single loop:

for key, val in d.items():
print val, key

This loop has two iteration variables because items returns a list of tuples and key, val is a tuple assignment that successively iterates through each of the key/value pairs in the dictionary.

For each iteration through the loop, both key and value are advanced to the next key/value pair in the dictionary (still in hash order).

The output of this loop is:

10 a
22 c
1 b

Again in hash key order (i.e. no particular order).

If we combine these two techniques, we can print out the contents of a dictionary sorted by the value stored in each key/value pair.

To do this, we first make a list of tuples where each tuple is (value, key). The items method would give us a list of (key, value) tuplesโ€“but this time we want to sort by value not key. Once we have constructed the list with the value/key tuples, it is a simple matter to sort the list in reverse order and print out the new, sorted list.

>>> d = {'a':10, 'b':1, 'c':22}
>>> l = list()
>>> for key, val in d.items() :
... l.append( (val, key) )
...
>>> l
[(10, 'a'), (22, 'c'), (1, 'b')]
>>> l.sort(reverse=True)
>>> l
[(22, 'c'), (10, 'a'), (1, 'b')]
>>>

By carefully constructing the list of tuples to have the value as the first element of each tuple, we can sort the list of tuples and get our dictionary contents sorted by value.

-Dr. Charles R. Severance (Author)