Python Language Operator module Itemgetter

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Grouping the key-value pairs of a dictionary by the value with itemgetter:

from itertools import groupby
from operator import itemgetter
adict = {'a': 1, 'b': 5, 'c': 1}

dict((i, dict(v)) for i, v in groupby(adict.items(), itemgetter(1)))
# Output: {1: {'a': 1, 'c': 1}, 5: {'b': 5}}

which is equivalent (but faster) to a lambda function like this:

dict((i, dict(v)) for i, v in groupby(adict.items(), lambda x: x[1]))

Or sorting a list of tuples by the second element first the first element as secondary:

alist_of_tuples = [(5,2), (1,3), (2,2)]
sorted(alist_of_tuples, key=itemgetter(1,0))
# Output: [(2, 2), (5, 2), (1, 3)]


Got any Python Language Question?