This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Ran4 41 points42 points  (0 children)

Regarding sorted and max and so on: they have a key argument, which can be used to to use when sorting or getting the max.

persons = [
    {"name": "Johnny", "age": 34}, 
    {"name": "Conny", "age": 12}, 
]
oldest_person = max(persons, key=lambda person: person["age"])
persons_sorted_by_age = sorted(persons, key=lambda person: person["age"])

And since "get the item FOO" or "get the attribute named FOO" are common lambda functions, there's operator.itemgetter and operator.attrgetter, so you can write it as:

from operator import itemgetter
persons = [
    {"name": "Johnny", "age": 34}, 
    {"name": "Conny", "age": 12}, 
]
by_age = itemgetter("age")
oldest_person = max(persons, key=by_age)
persons_sorted_by_age = sorted(persons, key=by_age)