[Python-Dev] operator.itemgetter with a callback method

Alexandre Fiori fiorix at gmail.com
Sun Jan 11 17:02:17 CET 2009


i was thinking about a possible improvement for the itemgetter
the documentation page shows simple examples like sorting a dictionary by
its integer values, like this:

>>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
>>> getcount = itemgetter(1)
>>> map(getcount, inventory)
[3, 2, 5, 1]
>>> sorted(inventory, key=getcount)
[('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]

let's suppose i have dictionary where items are lists (instead of integers),
and i want to sort it by the size of each list:

>>> friends = {
...  'alex': ['bob', 'jane'],
...  'mary': ['steve', 'linda', 'foo bar'],
...  'john': ['max']
... }
>>> sorted(friends.items(), key=itemgetter(1))
[('alex', ['bob', 'jane']), ('john', ['max']), ('mary', ['steve', 'linda',
'foo bar'])]

that doesn't work since itemgetter(1) will return a list, and that's not
useful for sorting.

i didn't look at the code, but i suppose itemgetter is something like this:

class itemgetter:
    def __init__(self, index):
        self.index = index

    def __call__(self, item):
        return tem[self.index]

in order for that sort (and possibly a lot of other things) to work
properly, we could add
a callback method for itemgetter, like this:

class itemgetter:
    def __init__(self, index, callback=None):
        self.index = index
        self.callback = callback

    def __call__(self, item):
        return self.callback and self.callback(item[self.index]) or

so, we could easly sort by the amount of data in each list, like this:

>>> sorted(friends.items(), key=itemgetter(1, callback=len))
[('john', ['max']), ('alex', ['bob', 'jane']), ('foo', ['bar', 'steve',

what do you guys think about it? please correct me if i'm wrong.

Ship ahoy! Hast seen the While Whale?
 - Melville's Captain Ahab
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20090111/4612d40b/attachment.htm>

More information about the Python-Dev mailing list