why should dict not be callable?

Brett Hoerner bretthoerner at gmail.com
Tue Oct 17 21:32:21 CEST 2006


georgeryo... at gmail.com wrote:
> A couple of times recently I've come across this problem:  I have a
> large list to sort and I need to the the "key=function" argument to
> sort appropriately.  But I actually have the key mapping in a big
> dictionary.

Is this what you mean?  I suppose the lambda is an "intermediary
function" ... but meh...

l = ['bob', 'dog', 'cat', 'apple']
d = {'bob': 7, 'dog': 0, 'cat': 14, 'apple': 3}

l.sort(lambda x,y: d[x] - d[y])

print l
['dog', 'apple', 'bob', 'cat']




More information about the Python-list mailing list