Your Own Key
key can be any function that takes one element and returns what to sort it by, including a function you write yourself. You need one for a list of tuples, such as the results of a game:
results = [("Anna", 12), ("Tom", 7), ("Eva", 15)]
print(sorted(results))[('Anna', 12), ('Eva', 15), ('Tom', 7)]Without a key, Python compares tuples the way it compares texts: by their first elements, and only when those are the same, by the second ones. So the results are sorted by name. To sort them by score, write a function that gets one result and returns its score:
def by_score(player):
return player[1]
results = [("Anna", 12), ("Tom", 7), ("Eva", 15)]
print(sorted(results, key=by_score, reverse=True))[('Eva', 15), ('Anna', 12), ('Tom', 7)]sorted() calls by_score() on each tuple (by_score(("Anna", 12)) returns 12, and so on) and sorts the tuples by these scores. Name the function after what it returns, and the call reads well: sorted by score.
A list of dictionaries works the same way, only the function reads a value by its key:
def by_price(product):
return product["price"]
products = [
{"name": "notebook", "price": 3},
{"name": "backpack", "price": 35},
{"name": "pencil", "price": 1}
]
for product in sorted(products, key=by_price):
print(product["name"], product["price"])pencil 1
notebook 3
backpack 35And a dictionary sorted by its values? sorted(scores) sorts only its keys. But .items() gives the pairs as tuples, (key, value), so by_score() from the second example sorts them by their values:
scores = {"Anna": 12, "Tom": 7, "Eva": 15}
for name, score in sorted(scores.items(), key=by_score, reverse=True):
print(name, score)Eva 15
Anna 12
Tom 7A typical mistake is a key function without return. It then returns None for every element, and Python can't compare None with None: the program ends with TypeError: '<' not supported between instances of 'NoneType' and 'NoneType'.
Instructions
- 1
Write a function
by_votes(pair). It gets one pair fromvotes.items(), a tuple such as("pizza", 8), and returns its number of votes. Use it to print the pairs from the fewest votes:print(sorted(votes.items(), key=by_votes)). The output should be[('salad', 2), ('soup', 4), ('pasta', 5), ('pizza', 8), ('burger', 11)]. Leave the line with the votes as it is: the exercise also runs your program with other votes. - 2
Below, print the result of the vote from the most votes: each food on its own line with its votes, for example
burger: 11. Go through the sorted pairs with aforloop with two variables.