Operator.itemgetter in Python

help on operator.itemgetter:

itemgetter(item, …) –> itemgetter object Return a callable object that fetches the given item(s) from its operand.

After, f=itemgetter(2), the call f(r) returns r[2].

After, g=itemgetter(2,5,3), the call g(r) returns (r[2], r[5], r[3]).

Threr are two tricks about this:

  • get dict values by keys
from operator import itemgetter
x = {'a': 1, 'b': 2, 'c': 3}
y = itemgetter('a', 'b')(x)  # y == (1, 2)
  • sorted dict keys by values
from operator import itemgetter
# y == [('b', 20), ('c', 30), ('a', 100)]
y = sorted(x.iteritems(), key=lambda item: item[1])
# z == ['b', 'c', 'a']
z = sorted(x, key=x.get)

more about sorted()

the key parameter specify a function to be called on each list element prior to making comparisons. The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes. A common pattern is to sort complex objects using some of the object’s indices as keys.