如何根据具有密钥的另一个列表来订购字典列表?

时间:2016-04-04 12:26:33

标签: python sorting

我有一些ID如下:

req_ids=['964','123','534','645','876','222']

我收到来自其他服务器的回复,不是以任何特定的顺序:

res_result = [{'id':'123', 'name':'Sachin'},
              {'id':'534', 'name':'Vipin'},
              {'id':'222', 'name':'Ram'},
              {'id':'645', 'name':'Anoop'},
              {'id':'964', 'name':'Sani'},
              {'id':'876', 'name':'John'}]

我需要在与req_ids相同的请求顺序中获取res_result

    [{'id':'964', 'name':'Sani'},
     {'id':'123', 'name':'Sachin'},
     {'id':'534', 'name':'Vipin'},
     {'id':'645', 'name':'Anoop'},
     {'id':'876', 'name':'John'},
     {'id':'222', 'name':'Ram'}]

如果可能的话,我如何使用内置的python函数代替编写我们自己的循环来执行此逻辑?

2 个答案:

答案 0 :(得分:5)

如果必须排序,请将键映射到整数,然后使用该映射进行排序:

id_to_pos = {key: i for i, key in enumerate(req_ids)}
sorted(res_result, key=lambda d: id_to_pos[d['id']])

演示:

>>> from pprint import pprint
>>> req_ids = ['964', '123', '534', '645', '876', '222']
>>> res_result = [{'id':'123', 'name':'Sachin'},
...               {'id':'534', 'name':'Vipin'},
...               {'id':'222', 'name':'Ram'},
...               {'id':'645', 'name':'Anoop'},
...               {'id':'964', 'name':'Sani'},
...               {'id':'876', 'name':'John'}]
>>> id_to_pos = {key: i for i, key in enumerate(req_ids)}
>>> sorted(res_result, key=lambda d: id_to_pos[d['id']])
[{'id': '964', 'name': 'Sani'}, {'id': '123', 'name': 'Sachin'}, {'id': '534', 'name': 'Vipin'}, {'id': '645', 'name': 'Anoop'}, {'id': '876', 'name': 'John'}, {'id': '222', 'name': 'Ram'}]
>>> pprint(_)
[{'id': '964', 'name': 'Sani'},
 {'id': '123', 'name': 'Sachin'},
 {'id': '534', 'name': 'Vipin'},
 {'id': '645', 'name': 'Anoop'},
 {'id': '876', 'name': 'John'},
 {'id': '222', 'name': 'Ram'}]

但是,您可以完全避免排序,已经拥有正确的顺序,您只需要从id键映射到词典(O(N)),然后拔出正确的字典(仍为O(N)):

id_to_dict = {d['id']: d for d in res_result}
[id_to_dict[id] for id in req_ids]

演示:

>>> id_to_dict = {d['id']: d for d in res_result}
>>> [id_to_dict[id] for id in req_ids]
[{'id': '964', 'name': 'Sani'}, {'id': '123', 'name': 'Sachin'}, {'id': '534', 'name': 'Vipin'}, {'id': '645', 'name': 'Anoop'}, {'id': '876', 'name': 'John'}, {'id': '222', 'name': 'Ram'}]
>>> pprint(_)
[{'id': '964', 'name': 'Sani'},
 {'id': '123', 'name': 'Sachin'},
 {'id': '534', 'name': 'Vipin'},
 {'id': '645', 'name': 'Anoop'},
 {'id': '876', 'name': 'John'},
 {'id': '222', 'name': 'Ram'}]

答案 1 :(得分:2)

>>> map({d['id']: d for d in res_result}.__getitem__, req_ids)
[{'id': '964', 'name': 'Sani'}, {'id': '123', 'name': 'Sachin'}, {'id': '534', 'name': 'Vipin'}, {'id': '645', 'name': 'Anoop'}, {'id': '876', 'name': 'John'}, {'id': '222', 'name': 'Ram'}]