Friday, June 12, 2009

Lambda function and class in python

I had a hash with hash value an object. I wanted to sort by one of the elements (integer) of the class.. Here is neat way..

class cl:
def __init__(self, val):
self.val = val

arr = {'a' : cl(10), 'ab' : cl(75), 'bd' : cl(50)}

g = lambda (x, y): y.val
for (x, y) in sorted(arr.iteritems(), key = g):
print x + ' ' + str(y.val)

No comments: