Kickstart 2020 with new opportunities! - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Searching
Sorting – sort()
7. Sorting orders for various variable types
Sorting – sorted()
Sorting – reverse() and reversed()
Summary

Instruction

Well done! We just mentioned that, by default, Python sorts all list elements in ascending order. What exactly does that mean for the various types of variables?

  1. Numbers are sorted from smallest to greatest. Consider this list:
    [8, -5, 0, 13.5, 1, 4.21, 2]
    It becomes the following when sorted:
    [-5, 0, 1, 2, 4.21, 8, 13.5]
  2. Strings are sorted in alphabetical order. Consider this list:
    ['Paul', 'john07', 'Anne2', 'K_a_t_e', 'jessi']
    It becomes the following when sorted:
    ['Anne2', 'K_a_t_e', 'Paul', 'jessi', 'john07']
  3. Tuples are sorted in lexicographic order. This means that Python compares the first elements of all tuples and sorts the tuples on that basis. If the first elements are identical, Python compares the second elements, etc. Consider this list:
    [('Anne', 21), ('Adam', 27), ('Kate', 19), ('Adam', 18)]
    It becomes the following when sorted:
    [('Adam', 18), ('Adam', 27), ('Anne', 21), ('Kate', 19)]

Note that all tuples should have the same dimension and the same type of elements in all the places. Suppose we tried to sort this list:

[(21, 'Anne'), ('Adam', 27)]

That would throw an error because Python can't compare 21 with 'Adam'.

Exercise

Write a function named get_sorted_list(input_dict) that accepts an input dictionary (as shown in the template code). The function should convert the dictionary into a list of tuples, where each tuple consists of two elements: (name, score).

The list should be returned sorted in ascending order by student name. For example, given the input dictionary from the template code, the list should return:

[
  ('Adam Smith', 23),
  ('Ann Keller', 97),
  ('Bryan Haynes', 32),
  ('Floyd Harrington', 56),
  ('Kathy Dennis', 78),
  ('Lucille Parks', 96)
]

Stuck? Here's a hint!

Create an empty list. Iterate over the dictionary and, for each element, append a tuple with that element's information to the list. Then, sort the list.