Sorting email addresses by domain

James Davies james at foomatic.net
Wed Nov 10 21:56:13 EST 2004


Split the email addresses on the '@', and store the domain in the key of a
dictionary, then sort the keys.

i.e. 
data = {}
for email in emails:
  (user, domain) = email.split('@')
  data[domain] = email
  keys = data.keys()
  keys.sort()
  return [data[x] for x in keys]


still not very elegant (would be nicer if list.sort() returned rather than
mutated the list).

Typed from memory, not checked. Possibly major errors in it :p

     

Peter Murray wrote:

> Hi! I hope someone can assist me, I have been using Python for a year or
> two, but I am not a programmer and only use it occasionally for small
> issues or just for fun. So I perhaps do not have the right 'mindset' to
> always see the answer to a problem.
> 
> Anyway, I have a list of email address and I want to sort them by domain.
> List.sort() wont work as this looks at the start of each address only. So
> the answer I have come up with is to split each email address around the
> "@", swap the position of the name and domain, build a new list with these
> and then sort this. Then switch positions back, and join with an "@". It
> works, but it seems a little inelegant. Is there a better, or easier way
> to do this?
> 
> Code is below. Thanks for any comments!
> 
> Pete.
> 
> def sortlist(addresslist):
>     l1 = []
>     for i in addresslist:
>         temp = i.split("@")
>         temp[0], temp[1] = temp[1], temp[0]
>         l1.append(temp)
>     l1.sort()
>     l2 = []
>     for i in l1:
> i[0], i[1] = i[1], i[0]
> temp = "@".join(i)
> l2.append(temp)
>     return l2




More information about the Python-list mailing list