[2.5.1.1/dictionary] Change sorting order?

Dave Angel davea at ieee.org
Fri Jan 22 15:49:32 CET 2010


Gilles Ganault wrote:
> Hello
>
> I use a dictionary to keep a list of users connected to a web site.
>
> To avoid users from creating login names that start with digits in
> order to be listed at the top, I'd like to sort the list differently
> every minute so that it'll start with the next letter, eg. display the
> list from A...Zdigits the first time, then B...ZAdigits, etc.
>
> That way, users have no incentive to create login names that start
> with either a digit or letter A.
>
> I see that dictionaries can be sorted using the... sort() method, but
> is it possible to have Python start sorting from a different letter?
>
> Thank you.
>
>   
Seems to me the other solutions I've seen so far are more complex than 
needed.  I figure you either want an unordered list, in which case you 
could use random.shuffle(), or you want a list that's sorted, but starts 
somewhere in the middle, at an arbitrary place, goes to the end, and 
wraps back to the beginning.  So use random.randint() to choose an index 
within the list, and concatenate two slices of the list, based on that 
index in reverse order.

And don't bother generating it each minute, but simply generate it each 
time you need it.  I doubt if the cost of generating it is much 
different than the cost of checking the time.

I guess there's a third possibility, that you don't want some of the G 
names at the beginning, and some at the end.  In that case, I'd generate 
the random index as above, then increment it till the first character of 
the item changes.  Use that index as your split point.

If you like any of these, I could elaborate with some code.  But each 
approach is pretty straightforward.

DaveA




More information about the Python-list mailing list