Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting of a list of dictionaries by name and assigning new key

I have a list of dictionaries of locations and towns, and their longitude and latitude that looks like this

STATIONS = [
{'lat': '78.27', 'name': 'Longyearbyen', 'location': 'Longyearbyen', 'lon': 
'15.49'},
{'lat': '71.03', 'name': 'Mehamn', 'location': 'Mehamn', 'lon': '27.83'},
{'lat': '70.67', 'name': 'Hammerfest', 'location': 'Hammerfest', 'lon': 
'23.67'},
{'lat': '70.37', 'name': 'Vardø', 'location': 'Vardø', 'lon': '30.91'},
{'lat': '69.79', 'name': 'Sørkjosen', 'location': 'Sørkjosen', 'lon': 
'20.95'},
{'lat': '69.65', 'name': 'Tromsø', 'location': 'Tromsø', 'lon': '18.94'},
{'lat': '69.61', 'name': 'Karasjok', 'location': 'Karasjok', 'lon': 
'25.30'} ]

`

I would like to take the towns and just sort them alphabetically and assign a new key to each of them from 0 onward. so the first town would have 0: 'town name', 1: 'second town name' and so on. I.e.

{0 : 'Town1', 1: 'town2' ....}

Is there a proper way of doing this? My head gets mixed up when there is a list of many dictionaries.

I have managed to sort the list by name by using

stations.sort(key=operator.itemgetter('name'))
like image 503
Joey Avatar asked Dec 31 '25 10:12

Joey


1 Answers

yes. extract only the town names, and use enumerate to generate the new index keys, in a dictionary comprehension:

STATIONS = [
    {'lat': '78.27', 'name': 'Longyearbyen', 'location': 'Longyearbyen', 'lon':
    '15.49'},
    {'lat': '71.03', 'name': 'Mehamn', 'location': 'Mehamn', 'lon': '27.83'},
    {'lat': '70.67', 'name': 'Hammerfest', 'location': 'Hammerfest', 'lon':
    '23.67'},
    {'lat': '70.37', 'name': 'Vardø', 'location': 'Vardø', 'lon': '30.91'},
    {'lat': '69.79', 'name': 'Sørkjosen', 'location': 'Sørkjosen', 'lon':
    '20.95'},
    {'lat': '69.65', 'name': 'Tromsø', 'location': 'Tromsø', 'lon': '18.94'},
    {'lat': '69.61', 'name': 'Karasjok', 'location': 'Karasjok', 'lon':
    '25.30'} ]

sorted_stations = {i:v for i,v in enumerate(sorted([x['name'] for x in STATIONS]))}

alternately using map and operator.itemgetter that avoids the comprehension:

sorted_stations = {i:v for i,v in enumerate(sorted(map(operator.itemgetter('name'),STATIONS)))}

result:

{0: 'Hammerfest', 1: 'Karasjok', 2: 'Longyearbyen', 3: 'Mehamn', 4: 'Sørkjosen', 5: 'Tromsø', 6: 'Vardø'}

that said, using indexes as keys is slightly overkill when sorted(x['name'] for x in STATIONS) generates a list which you can access by indexes. It's only useful when creating a "sparse" list.

like image 69
Jean-François Fabre Avatar answered Jan 03 '26 05:01

Jean-François Fabre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!