Python通过键值列表对字典进行排序

时间:2018-10-19 09:28:05

标签: python python-3.x

我有一个按排序顺序排列的值列表:

observer = new FileObserver(pathToWatch) { // set up a file observer to watch this directory on sd card
        @Override
        public void onEvent(int event, String fileName) {
            if (fileName == null) {
                return;
            }
            //a new file or subdirectory was created under the monitored directory

            if ((FileObserver.DELETE & event) != 0) {
                //handle deleted file
                Log.e(TAG, "onEvent: DELETE");
                Log.e(TAG, "onEvent:exists(): " + new File(pathToWatch + fileName).exists());
            }
        }
    };
    observer.startWatching();

我想根据订单对数据(按“名称”排序)

2 个答案:

答案 0 :(得分:2)

您可以这样:

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

答案 1 :(得分:1)

我会提前创建一个订单映射以使关键功能更快:

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))