ExplodingGayFish :
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?
Heap Overflow :
O(n) solution:
>>> [*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'}]
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=360567&siteId=1