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?