Q: listsort and dictsort - official equivalents?

BJörn Lindqvist bjourne at gmail.com
Tue Jun 19 20:57:30 EDT 2007


> In python I must kick off a sort on the line before I start the
> iteration.  (This does make sense because at the end of the day the sort
> has complete BEFORE the for loop can proceed - that is... until the day
> when python lists have a secondary index ;-).
>
> group_list=group_dict.keys()
> group_list.sort()
> for group in group_list: # do
>   print group,group_dict[group]
> # done
>
> I am sure python has a more concise way of doing this, any hints?

for group in sorted(open("/etc/group")):
    print group,

It's not true that the sort must complete (or that the whole file must
be read for that matter), Python has cool generators which makes the
above possible. You can even sort by the gid:

for group in sorted(open("/etc/group"), key = lambda x: int(x.split(':')[2])):
    print group,

-- 
mvh Björn



More information about the Python-list mailing list