Help with dictionary

Thorsten Kohnhorst monsterkodi at gmx.net
Thu Jun 5 10:56:42 CEST 2003


Hello Jim,

> 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?

If you want a *list* of the items in your dictionary sorted by their 
keys, you could simply do something like this:

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

 >>> l = d.items()
 >>> l.sort()

 >>> print l
[((0, (19697, 19763)), 4100), ((1, (21353, 21418)), 3900), ((2, (53006, 
53164)), 3800)]

I hope that helps,
yours kodi








More information about the Python-list mailing list