Reputation: 369
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?
Upvotes: 0
Views: 1849
Reputation: 5223
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'})]
Upvotes: 2