sort a dictionary by keys in specific order

Tim Chase python.list at tim.thechases.com
Fri May 26 13:42:32 EDT 2006


> hi i have a normal dictionary with key and value pairs. now i wanna
> sort by the keys BUT in a specific order i determine in a list !? any
> ideas
> 
> dic = {'key1':'value1', 'key2':'value2', 'key3':'value3'}
> 
> list = [key2, key3, key1]

1)  it's bad practice to shadow the list() command...funky stuff 
can happen.

2) I presume your list is a list of strings, not of references:

	order = ['key2', 'key3', 'key1']

3) As a dictionary is an unordered collection, I presume you want 
a resulting list of key/value pairs.

If both #2 and #3 hold, you can use

	results = [(k,dic[k]) for k in order]

which will return a list of tuples in the desired key order.

-tkc








More information about the Python-list mailing list