[Tutor] Sorting a dictionary
Kent Johnson
kent37 at tds.net
Fri Nov 4 12:18:20 CET 2005
Johan Geldenhuys wrote:
> Thanks, Danny.
>
> You see, I didn't put all the keys and values in the dicionary manually.
> It was generated while parsing a file with some Python code, that's why
> the dict is not in order. I just want to do it to read easier and look
> something up.
You want the dict to be sorted in your Python source code, is that it? The simplest thing might be to use an editor with a sort function. If the code was generated from Python then you can use Danny's method to sort and change the output. Something like this:
for k, v in sorted(d.items()):
print ' %r : %r,' % (k, v)
Kent
More information about the Tutor
mailing list