python - Sort a list of dictionary with order of specific key
问题描述
I have a list
of dict
like this:
data = [{"uid": "a1", "name": "b1"},
{"uid": "a3", "name": "b3"},
{"uid": "a4", "name": "b4"},
{"uid": "a5", "name": "b5"}]
Now I want to sort that list
with the order of the uid
field like this:
uid_order = ['a1', 'a5', 'a3', 'a4']
Which means the output should be:
[{"uid": "a1", "name": "b1"},
{"uid": "a5", "name": "b5"},
{"uid": "a3", "name": "b3"},
{"uid": "a4", "name": "b4"}]
Of course, I can create a new empty list
then use 2 for
loops to check and add every element, but is there any elegant way (or better complexity) to do this?
解决方案
O(n) 解决方案:
>>> [*map({d['uid']: d for d in data}.get, uid_order)]
[{'uid': 'a1', 'name': 'b1'},
{'uid': 'a5', 'name': 'b5'},
{'uid': 'a3', 'name': 'b3'},
{'uid': 'a4', 'name': 'b4'}]
推荐阅读
- excel - 上个月召回格式
- javascript - 无限循环 GoogleAppScript
- python - 为什么当代码相同时我的输出不同?
- applescript - 如何识别字符串中的 6 个连续数字?
- javascript - React Router V4,不匹配Routes中第一个父级下的任何内容
- powershell - 在 Powershell 中将两个数组输出转换为具有动态更新的表
- google-apps-script - Google Appmaker 中的 JDBC 连接 - 不想在脚本中存储密码
- php - 过滤数据后出现 JSON 错误,但页面加载正常但未过滤
- javascript - 在 jQuery 中选择下一个“选择”项
- android - 未解决的参考:活动错误