Jianli Cheng Jianli Cheng - 4 months ago 8
Python Question

How to get index of a sorted list of dictionary in python?

So I know the way to sort a list of dict but I just cannot figure out how to get the index at the same time. Suppose I have a dict like this:

cities = [{'city': 'Harford', 'state': 'Connecticut'},
{'city': 'Boston', 'state': 'Massachusetts'},
{'city': 'Worcester', 'state': 'Massachusetts'},
{'city': 'Albany', 'state': 'New York'},
{'city': 'New York City', 'state': 'New York'},
{'city': 'Yonkers', 'state': 'Massachusetts'}]


I can sort this dict by 'state' using:

new_cities = sorted(cities, key=itemgetter('state'))


And get:

cities = [{'city': 'Harford', 'state': 'Connecticut'},
{'city': 'Boston', 'state': 'Massachusetts'},
{'city': 'Worcester', 'state': 'Massachusetts'},
{'city': 'Yonkers', 'state': 'Massachusetts'},
{'city': 'Albany', 'state': 'New York'},
{'city': 'New York City', 'state': 'New York'}]


But how can I get the index of the list at the same time?

Answer
new_cities = sorted(enumerate(cities), key=lambda x: x[1]['state'])

enumerating it first will give you the index of the original cities list which can then be sorted.

>>> new_cities
[(0, {'city': 'Harford', 'state': 'Connecticut'}),
 (1, {'city': 'Boston', 'state': 'Massachusetts'}),
 (2, {'city': 'Worcester', 'state': 'Massachusetts'}),
 (5, {'city': 'Yonkers', 'state': 'Massachusetts'}),
 (3, {'city': 'Albany', 'state': 'New York'}),
 (4, {'city': 'New York City', 'state': 'New York'})]
Comments