简体   繁体   中英

Python sort dictionary by a list of key values

I have a list of values that is the sort order:

order = ['foo', 'bar']
data = [{'name': 'bar', 'someData': 'someValue'}, {'name': 'foo', 'someData': 'someValue'}]

I would like to sort data (by 'name') based on order

您可以像这样去:

sorted(data, key = lambda x: order.index(x["name"]))

I would create an order mapping in advance to make the key function faster:

def create_key(order, field='name'):
    order_map={v: i for (i, v) in enumerate(order)} 
    def key(elem):
       return order_map[elem[field]]
    return key

data.sort(key=create_key(order))

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