[2.5.1.1/dictionary] Change sorting order?

Jean-Michel Pichavant jeanmichel at sequans.com
Fri Jan 22 14:09:43 CET 2010


Jean-Michel Pichavant wrote:
> 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
Sorry, the code I provided produce this output:

['1a', 'a', 'ac', 'av', 'b', 'c']
['a', 'ac', 'av', 'b', 'c', '1a']
['b', 'c', '1a', 'a', 'ac', 'av']
['c', '1a', 'a', 'ac', 'av', 'b']
['1a', 'a', 'ac', 'av', 'b', 'c']

which is actually what you are searching for. I just messed up with my 
ipython shell history :o)

JM



More information about the Python-list mailing list