[2.5.1.1/dictionary] Change sorting order?
Jean-Michel Pichavant
jeanmichel at sequans.com
Fri Jan 22 08:06:35 EST 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.
>
Here is one possible solution
l = ['1a', 'a', 'b','c','av','ac'] # you mentioned a dictionary in your
post, if so, l = myDict.keys()
l.sort() # sort your list once and for all
for start in '1abcd':
result = [name for name in l if name[0] >= start] + [name for name
in l if name[0] < start]
print result
['1a', 'a', 'b', 'c', 'av', 'ac']
['a', 'b', 'c', 'av', 'ac', '1a']
['b', 'c', '1a', 'a', 'av', 'ac']
['c', '1a', 'a', 'b', 'av', 'ac']
['1a', 'a', 'b', 'c', 'av', 'ac']
Jean-Michel
More information about the Python-list
mailing list