简体   繁体   中英

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?

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'})]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM