Tag Archives: Lambdas

Sort a list of dictionaries by a key In all of them

If you have a list of dictionaries like this:

fruit = [{'Name': 'Banana', 'Colour': 'Yellow', 'Shape': 'Bent'},
            {'Name': 'Apple', 'Colour': 'Red', 'Shape': 'Round'}]

And you want to sort them by the Name key, you can do one of two things.

Method 1: Use a lambda

print sorted(fruit, key=lambda k: k['Name'])

Method 2: Use itemgetter

from operator import itemgetter
print sorted(fruit, key=itemgetter('Name')) 

Lambda expressions in C++

The STL provides the useful std::for_each, and std::transform algorithms, which make it easy to iterate over sequences without needing to write a loop. They’re especially useful when you’re using existing free functions, static functions, and member functions:

// If v contains MyClass objects
std::for_each(v.begin(), v.end(), &FreeFunction);
std::for_each(v.begin(), v.end(), &MyClass::StaticFunction);
std::for_each(v.begin(), v.end(), std::mem_fun_ref(&MyClass::MemberFunction));

// If v contains pointers to MyClass objects
std::for_each(v.begin(), v.end(), std::mem_fun(&MyClass::MemberFunction));

Often however, there isn’t an existing function to do what you want, and you end up defining a function or function object just where you use it:

namespace {
    struct FunctionObject {
        void operator()(MyClass& m) {
            // Do something to m here

std::for_each(v.begin(), v.end(), FunctionObject());

Things can get more awkward still when you have local variables that you want to use in the operation you’re performing:

namespace {
    struct FunctionObject2 {
        typedef MyClass first_argument_type;
        typedef int second_argument_type;
        typedef void result_type;
        void operator()(const MyClass& m, int x) const 
            // Do something with m and x here

int x;
std::for_each(v.begin(), v.end(), std::bind2nd(FunctionObject2(), x));

This is rather complicated for a one-shot piece of code. It would be much better to be able to define the operation to be performed in-line at the point of use, and this is what lambda expressions allow you to do.

For example, this lambda expression replaces our first example:

std::for_each(v.begin(), v.end(), [](MyClass& m) { /* Do something to m here*/ });

The [] can capture local variables, making them available within the body of the lambda expression. This is how our second example would look:

int x;
std::for_each(v.begin(), v.end(), [x](MyClass& m) { /* Do something with m and x here*/ });