sorting list by multiple criteria and grouping alphabetically in python

Ahamed Farook farookrceg at gmail.com
Sat Apr 18 03:56:46 EDT 2015


I have a list named "lsNearCities" which contains "states" and "cities" in
it. And I write the values in the list to csv where the column will be in
the order of city and state. And also I did sorting based on the state
first and cities second. Now I want the csv to be printed as shown below.
How can it be done? Please help me in this.

*Csv at present*

Abbeville TX

Bakerhill TX

Abernant GA

Bangor GA

Alabaster AL

Berry AL

*Csv i needed*

Alabaster AL

Berry AL

Abernant GA

Bangor GA

Abbeville TX

Bakerhill TX

And my code is

lsNearCities = []
idx = layer.fieldNameIndex('name')  #name of the attribute column with
the cities in it
idx1 = layer.fieldNameIndex('state')
nearCity = f.attributes()[idx]
state = f.attributes()[idx1]
state_and_cities = nearCity + "," + str(state)
lsNearCities.append(state_and_cities)
sorted(lsNearCities, key=operator.itemgetter(1,0))
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20150418/aae99a0e/attachment.html>


More information about the Python-list mailing list