[Tutor] Sort dictionaries
Kent Johnson
kent37 at tds.net
Mon Nov 15 22:32:46 CET 2004
David Holland wrote:
> Is there a built command to sort a dictionary keys or
> values by their length or do I have to write a
> function to do it myself ?
In Python 2.4 you can use sort with the builtin len as the key:
>>> d = dict(aaa='aaa', bb='bb', c='c')
>>> d
{'c': 'c', 'aaa': 'aaa', 'bb': 'bb'}
>>> k=d.keys()
>>> k
['c', 'aaa', 'bb']
>>> k.sort(key=len)
>>> k
['c', 'bb', 'aaa']
In Python 2.3 the usual way to do this is with the
'decorate-sort-undecorate' idiom:
Make a helper list containing tuples. The first element of the tuple is
what you want to sort on, the second element is the actual data:
>>> l = [ (len(key), key) for key in d.keys() ]
>>> l
[(1, 'c'), (3, 'aaa'), (2, 'bb')]
Sort the helper list:
>>> l.sort()
>>> l
[(1, 'c'), (2, 'bb'), (3, 'aaa')]
Extract the original list:
>>> [ key for (keylen, key) in l]
['c', 'bb', 'aaa']
You could also write a comparison function and pass it to the sort, but
that is not recommended in general, it is much slower than DSU.
BTW this is really a question about lists, not dictionaries - d.keys()
is a list, as are d.values() and d.items().
Kent
More information about the Tutor
mailing list