1 of 21

Itemgetter and Sorting!

2 of 21

Logistics

  • Written check-in 7 due Friday Nov 14!
  • Resubmissions due Friday Nov 14
  • HW4 due Friday Nov 14
    • Submitting on Gradescope
    • Wait for autograder!
  • Coding practice 7 due Sunday, Nov 16!

3 of 21

Lecture Preview: Sorting

4 of 21

.sort()

listname.sort() sorts a list

Example:

Output:

lst = [2, 1, 3]

lst.sort()

print(lst)

[1, 2, 3]

5 of 21

sorted()

sorted(listname) returns a sorted copy of the list

Example:

Output:

lst1 = [2, 1, 3]

lst2 = sorted(lst1)

print(lst1)

print(lst2)

[2, 1, 3]

[1, 2, 3]

6 of 21

Note About In Place Functions

insert(), extend(), reverse(), and sort() are all called in place functions.

Example:

Output:

In-place” means that the list is modified, but the result it returns is None

lst = [2, 3, 1]

result = lst.sort()

print(result)

print(lst)

None

[1, 2, 3]

7 of 21

Lecture Preview: Itemgetter

8 of 21

Why Do We Care About Itemgetter?

  • Very easy way to sort values on multiple attributes
  • Way to sort dictionaries into a list
    • if my_dict is a dictionary, then list(my_dict.items()) will return a list of key value tuple pairs!
  • Super important for hw5!

9 of 21

Itemgetter

Itemgetter returns a function:

from operator import itemgetter

get_3rd_item = itemgetter(2)

get_3rd_item([7, 3, 8]) -> 8

# this is the same as

itemgetter(2)([7, 3, 8]) -> 8

10 of 21

Sorting with Itemgetter in General

  • Useful for when you have a list of tuples where every item inside those tuples corresponds to a particular feature
    • ex: the element at index 0 of every tuple is a name, the element at index 1 of every tuple is an age)
    • lst = [('Anne', 5), ('Bob', 6), ('Carl', 3), ('Elisa', 2), ('Diana', 2)]

  • If you want to sort with the feature in the tuple at the index i, do so like this:
    • sorted_lst = sorted(lst, key = itemgetter(i))

  • Sort by the “least important” feature first (ie a tie breaker), the more important features last

11 of 21

Sorting with Itemgetter

lst = [('Anne', 5), ('Bob', 6), ('Carl', 3), ('Elisa', 2), ('Diana', 2)]

# sort alphabetically by name

alphabetical_lst = sorted(lst, key = itemgetter(0))

# sort by the number (lowest number first)

sorted(lst, key = itemgetter(1))

# sort by the number (highest number first)

sorted(alphabetical_lst, key = itemgetter(1), reverse = True)

12 of 21

Sorting with Itemgetter Based on 2 Criteria

lst = [('Anne', 5), ('Bob', 6), ('Carl', 3), ('Elisa', 2), ('Diana', 2)]

# sort by the number (highest number first), break ties alphabetically

# alphabetize first

sorted_lst = sorted(lst, key = itemgetter(0))

# then sort by number

sorted_lst = sorted(sorted_lst, key = itemgetter(1), reverse = True)

13 of 21

Section Handout Problems

14 of 21

Problem 1

What output is produced after running the following piece of code?

from operator import itemgetter

data = [ ("Fred", 3, 5),

("Zeke", 5, 3),

("Sam", 5, 6),

("Mary", 3, 5),

("Ann", 7, 8) ]

def some_key(x):

return len(x[0])

print(sorted(data, key=some_key))

print(sorted(data, key=itemgetter(2), reverse=True))

15 of 21

Problem 1

[('Sam', 5, 6), ('Ann', 7, 8), ('Fred', 3, 5), ('Zeke', 5, 3), ('Mary', 3, 5)]

[('Ann', 7, 8), ('Sam', 5, 6), ('Fred', 3, 5), ('Mary', 3, 5), ('Zeke', 5, 3)]

16 of 21

Problem 2

a. Given a list of tuples in the form (name, age), using itemgetter, return a list names and ages sorted alphabetically in one line of code

b. Given a list of tuples in the form (name, age), using itemgetter, return a list names and ages sorted by increasing age in one line of code

17 of 21

Problem 2

a. alphabetical_lst = sorted(lst, key = itemgetter(0))

b. youngest_to_oldest = sorted(lst, key = itemgetter(1))

18 of 21

Problem 2

c. Using itemgetter, define a function called find_oldest that takes in a list of tuples in the form (name, age) and returns a list of tuples belonging to the oldest people. If there is a tie, return a list of the names and ages of the people sharing the same (oldest) age in a new list in alphabetical order.

given age_list = [ ("Tom", 19), ("Max", 26), ("James", 12), ("Alice", 26), ("Carol", 10) ],

find_oldest(age_list) would return

[("Alice", 26), ("Max", 26)]

19 of 21

Problem 2

def find_oldest(age_list):

sort_name = sorted(age_list, key=itemgetter(0))

sort_age = sorted(sort_name, key=itemgetter(1), reverse=True)

oldest_age = sort_age[0][1]

ret_list = []

for pair in sort_age:

if(pair[1] == oldest_age):

ret_list.append(pair)

else:

return ret_list # return early since it is sorted

return ret_list

20 of 21

Problem 3

  1. You are given a list of dictionaries representing the scientific and common names of various plants. Write a function called unique_species(plants) that takes in a list of dictionaries and returns a list of all of the unique species by their scientific name sorted alphabetically.

cactus = [{“scientific name”: “Kroenleinia grusonii”,”common

name”: “golden barrel cactus”},

{“scientific name”: “Kroenleinia grusonii”,”common name”: “golden ball”},

{“scientific name”: “Carnegiea gigantea”,”common name”: “saguaro”}]

Should return:

[“Carnegiea gigantea”, “Kroenleinia grusonii”]

21 of 21

Problem 3

def unique_species(plants):

species = set()

for name in plants:

species.add(name["scientific name"])

return sorted(list(species))