Hozer Central

Mon, 29 Oct 2007

Sorting a python list of dictionaries

Lately I've been using lists of dictionaries a lot to store data to be processed sequentially. More often than not, the data gets loaded into the list in an ordered state, but I needed a way to force it to be ordered by a key of the dictionary. Luckily the sort() list function takes as an argument a function to do the comparison for me. Since the comparison is just a simple is this key less than another key I made my first venture into lambda functions:

l = [ {"name": "1234", "attribute1": "this is an attribute", "attribute2": "this is another"},
        {"name": "4325", "attribute1": "this is an attribute", "attribute2": "this is another"},
        {"name": "3145", "attribute1": "this is an attribute", "attribute2": "this is another"} ]

l.sort( lambda x, y: cmp( x["name"], y["name"] ) )

Ok, so i'll stop lying. The list of dictionaries is a list of Networker NSR Client entries. Each Networker entries is a dictionary relating to the attribute: value; of a Networker client. I need to sort this list so when we have multiple clients for the same server, they appear together when I process them. Using a lambda function as the function to pass to sort() accomplishes this since the lambda function is only calling the cmp() function on the 2 name attributes of 2 clients.

Quick, easy and reliable. Happy Hacking!

posted at: 23:35 | permanent link to this entry

< October 2007
MoTuWeThFrSaSu
1 2 3 4 5 6 7
8 91011121314
15161718192021
22232425262728
293031    

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License .

Powered by PyBlosxom.

Icons from the Tango Project.