[2.5.1.1/dictionary] Change sorting order?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Jan 22 14:24:05 CET 2010


On Fri, 22 Jan 2010 13:17:44 +0100, 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.

If you want to prohibit users from starting their login names with a 
digit, prohibit them from creating a login name with a digit.


> I see that dictionaries can be sorted using the... sort() method, but is
> it possible to have Python start sorting from a different letter?

You can write a customer sort routine by using the key parameter to sort, 
which will probably be messy. What I'd do is keep 27 lists of user names, 
according to the first letter (26 letters from A to Z, plus one extra):


users = [  # keep separate lists for each starting letter
    ['aaron', 'avril', 'adam'], 
    ['betty', 'bob'],
    ['craig', 'cathy'],
    ['danni', 'da5id', 'donna'],
    # ... and so on
    ['zoe', 'zach'],
    ['4dam', '1-4m-t00-c001']
    ]

# add a new user
users[3].append('daniel')


Sort each one individually, and display them in whatever order you like:


def display(start=0):
    start = start % 27
    all = users[start:] + users[:start]
    for l in all:
        l.sort()
        print l

And in use:

>>> display(0)
['aaron', 'adam', 'avril']
['betty', 'bob']
['cathy', 'craig']
['da5id', 'daniel', 'danni', 'donna']
['zach', 'zoe']
['1-4m-t00-c001', '4dam']
>>>
>>> display(3)
['da5id', 'daniel', 'danni', 'donna']
['zach', 'zoe']
['1-4m-t00-c001', '4dam']
['aaron', 'adam', 'avril']
['betty', 'bob']
['cathy', 'craig']



-- 
Steven



More information about the Python-list mailing list