Sort dictionary data

xtian xtian at toysinabag.com
Mon May 20 19:39:16 EDT 2002


Marcus Laranjeira <m.laranjeira at datacraft.com.br> wrote in message news:<mailman.1021918373.13410.python-list at python.org>...
> All,
> 
>    I have a dictionary that I need to be sorted. the current structure is :
> 
> dic { 'aaa', 1, 'bbb', 1, 'ccc', 3, 'ddd', 2, 'eee', 1} 
> 
> and I need this to be sorted and the final dictionary should be:
> 
> dic { 'aaa', 1, 'bbb', 1, 'eee', 1, 'ddd', 2, 'ccc', 3}
> 
> does anyone knows how can this be done ? Is there any ready module to do
> such sorting ?

Hi Marcus -
Dictionaries are effectively unsorted, for performance reasons - keys
are stored in the dict at the locations of their hash values. If you
want the items in the dict sorted, you'll need to extract them from
the dictionary (using .items()) and sort them before you use them.

Simple approach (using sorter function):
>>> def sorter(x, y):
	return cmp(x[1],y[1])

>>> i = dic.items()
>>> i
[('eee', 1), ('aaa', 1), ('bbb', 1), ('ccc', 3), ('ddd', 2)]
>>> i.sort(sorter)
>>> i
[('eee', 1), ('aaa', 1), ('bbb', 1), ('ddd', 2), ('ccc', 3)]

... or by Schwartzian transform (decorate-sort-undecorate):
>>> def flip((x,y)):
	return y,x

>>> i = dic.items()
>>> i
[('eee', 1), ('aaa', 1), ('bbb', 1), ('ccc', 3), ('ddd', 2)]
>>> i = [flip(t) for t in i]
>>> i
[(1, 'eee'), (1, 'aaa'), (1, 'bbb'), (3, 'ccc'), (2, 'ddd')]
>>> i.sort()
>>> i = [flip(t) for t in i]
>>> i
[('aaa', 1), ('bbb', 1), ('eee', 1), ('ddd', 2), ('ccc', 3)]

If the list you're sorting is large, using the Schwartzian transform
ensures that the sort is done by built in comparison, rather than
calling the Python sorter function O(n*logn) times.

(I love that you can do tuple unpacking in argument lists - reminds me
of the pattern matching in Haskell and Erlang!)

Hope that helps,
xtian



More information about the Python-list mailing list