You are here

Dictionaries and tuples

24 February, 2015 - 09:51

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

>>> 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.