[2.5.1.1/dictionary] Change sorting order?

Gilles Ganault nospam at nospam.com
Sun Jan 24 16:33:39 EST 2010


On Fri, 22 Jan 2010 13:17:44 +0100, Gilles Ganault <nospam at nospam.com>
wrote:
>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.

Thanks everyone for the great feedback. I ended up using
- a list instead of a dictionary to hold the list of names
- use the random library to pick a character from which to start
listing names (simpler than saving the next letter into a file, and
starting from this the next time the loop is gone through)

For those interested, here's some working code:

==========
import random

connected =
["_test","-test","0test","1test","Aa","Aab","Bb","Bbbbb","Cc","Ccaaaaaa"]
connected.sort()

#Fill list with non-duplicate first letter of all items
characters=[]
for name in connected:
	char = name[0]
	#if this character not in list, add to array
	if not char in characters:
		characters.append(char)

#Pick a random character from which to start iterating
index = random.randint(0,len(characters)-1)
startch = characters[index]
print "Will start from %s" % startch

#Go through list starting with items that start with 'starch', and
rotate from beginning
result = [name for name in connected if name[0] >= startch] + [name
for name in connected if name[0] < startch]
print result
==========

Thanks again.



More information about the Python-list mailing list