Help with dictionary
Raymond Hettinger
vze4rx4y at verizon.net
Thu Jun 5 13:59:48 EDT 2003
[Jim Shady]
> I have a dictionary of the sort:
>
> {(1, (21353, 21418)): 3900, (2, (53006, 53164)): 3800, (0, (19697,
> 19763)): 4100}
Dictionaries have an arbitrary ordering and so they can't be
sorted directly.
> 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}
Make a copy of the dictionary into a list of items. Then, sort the list:
>>> d = {(1, (21353, 21418)): 3900, (2, (53006, 53164)): 3800, (0, (19697,
19763)): 4100}
>>> it = d.items()
>>> it.sort()
>>> it
[((0, (19697, 19763)), 4100), ((1, (21353, 21418)), 3900), ((2, (53006, 53164)),
3800)]
Raymond Hettinger
More information about the Python-list
mailing list