Help with dictionary

Anand Pillai pythonguy at Hotpop.com
Thu Jun 5 07:55:17 EDT 2003


I dont get what you mean by 'sorting' a dictionary.
You can sort a list or an array because there is a specific
order in these structures. But I dont see any point in trying
to sort a dictionary. 

The following code will give you a list with the keys
sorted as you need it:

d={(1, (21353, 21418)): 3900, (2, (53006, 53164)): 3800, (0, (19697,
19763)): 4100}

newd=d.keys()
l=list(newd)
l.sort()

lnew=[]
for key in l:
    lnew.append((key,d[key]))

print lnew

# You get the output 
[((0, (19697, 19763)), 4100), ((1, (21353, 21418)), 3900), ((2,
(53006, 53164)), 3800)]

Now if you try to get the dictionary of this, "logically" you should
expect

{(0, (19697, 19763)): 4100, (1, (21353, 21418)): 3900, (2, (53006,
 53164)): 3800}

But what you get is,
print dict(lnew)

{(0, (19697, 19763)): 4100, (2, (53006, 53164)): 3800, (1, (21353,
21418)): 3900}

I dont see any point in trying to spend time over this problem.
Instead
use the sorted list for your purposes and finally create the
dictionary
using dict() if you want the keys sorted.

If there was any need for a 'sorted dictionary' the language designers
would have provided that. 

Anand Pillai

iamshady at rediffmail.com (Jim Shady) wrote in message news:<9afd3f36.0306042301.5243a9e8 at posting.google.com>...
> Hello,
> 
> I have a dictionary of the sort:
> 
> {(1, (21353, 21418)): 3900, (2, (53006, 53164)): 3800, (0, (19697,
> 19763)): 4100}
> 
> I need to re-sort this dictionary with the first element of the tuple
> in the keys. A sorted dictionary of the above would be:
> 
> {(0, (19697, 19763)): 4100, (1, (21353, 21418)): 3900, (2, (53006,
> 53164)): 3800}
> 
> Could somebody help me with the algorithm/logic to accomplish this?
> 
> Thanks in advance!
> 
> Jim




More information about the Python-list mailing list