sort values from dictionary of dictionaries python 2.4

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Mon Nov 9 23:52:42 EST 2009


On Mon, 09 Nov 2009 06:02:09 -0800, J Wolfe wrote:

> Hi,
> 
> I would like to sort this dictionary by the values of the inner
> dictionary ‘ob’ key.

You can't sort dictionaries in Python, because they are unordered hash 
tables. Giving up the ability to store items in order is one of the 
things which makes them so fast.

You have five choices:

(1) Create your own implementation of a sortable dictionary, perhaps 
using a red-black tree or similar. Unless you write it in C, expect it to 
be massively slower than the built-in dict type. If you write it in C, 
expect it to be merely slower than the built-in dict type.

(2) Write small helper functions that sort the keys from the dict when 
you need them sorted. Since you (probably) only have a small number of 
items in each dict, it should be fast.

(3) Use a subclass of dict that sorts the items as needed.

(4) Give up on using dictionaries for this, and use some other mapping, 
like a list of (key, value) tuples. Expect it to be massively slower than 
the built-in dict type.

(5) Give up on the need to have them sorted.


My advice is to go with #2, 3 or 5. Here's a basic version of 3 to get 
you started:

class SortedDict(dict):
    # Untested.
    def items(self):
        """Return items of self in sorted order."""
        L = super(SortedDict, self).items()
        L.sort()
        return L

You may even find a version with an appropriate licence you can freely 
use if you google for "Python Sorted Dict".




-- 
Steven



More information about the Python-list mailing list