Dictionaries are (before Python 3.6, anyway) data structures without an inherent order. Write a one-line Python statement returning a list of (key, value) pairs sorted by key. Assume that all keys have the same data type (why is this important?) Repeat the exercise to produce a list ordered by dictionary values.
To return a sorted list of (key, value) pairs from a dictionary:
>>> d = {'five': 5, 'one': 1, 'four': 4, 'two': 2, 'three': 3}
>>> d
{'four': 4, 'one': 1, 'five': 5, 'two': 2, 'three': 3}
>>> sorted([(k, v) for k, v in d.items()])
[('five', 5), ('four', 4), ('one', 1), ('three', 3), ('two', 2)]
Note that sorting the list of (key, value) tuples requires that the keys all have data types that can be meaningfully ordered. This approach will not work, for example, if the keys are a mixture of integers and strings since (in Python 3) there is no defined order to sort these types into: a TypeError: unorderable types: int() < str()
exception will be raised.
To sort by value we could sort a list of (value, key) tuples, but to keep the returned list as (key, value) pairs, use
>>> sorted([(k, v) for k, v in d.items()], key = lambda item: item[1])
[('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)]
The key
argument to sorted
specifies how to interpret each item in the list for ordering: here we want to order by the second entry in each (k, v)
tuple to order by value.