sort a dictionary by keys in specific order

Tim Chase python.list at tim.thechases.com
Fri May 26 20:08:05 CEST 2006


 > how do i get the result back into the dictionary ?

Well, if you must, if you've just got the results in my
previous post, you can take them and shove them back into a
dict with

	results = [('key1','value1'),('key2','value2)]
	newDict = dict(results)

If you're not doing anything with that the resulting list of
ordered key/value pairs (such as inserting, printing,
whatever), then skip the whole matter:

	newDict = dic

:)

HOWEVER...as I noted, a dictionary is an INHERENTLY UNSORTED
COLLECTION.  There are some wrapper-classes around that will
feign sortedness if you want them, but they may not handle
your custom sortedness constraint.

There are few reasons for a sorted dict.  Most of them
regard displaying them.  If this is the case, just do the
sorting/selection of the items before you print:

	print "\n".join([dic[k] for k in order])

Other reasons might involve dependancies, where some process
requires that you access the keys in a particular order.
Just order them before you call the process.

-tkc









More information about the Python-list mailing list