根据其他数组对python中的字典数组进行排序

时间:2019-06-25 13:26:04

标签: python sorting

我有一个字典[{'id': 1, 'name': 'one'}, {'id':2, 'name': 'two'}, {'id': 3, 'name': 'three'}]和一个ID为[3, 1, 2]的数组

预期结果是

[{'id': 3, 'name': 'three'}, {'id': 1, 'name': 'one'}, {'id': 2, 'name': 'two'}]

最好的方法是什么?

我的代码基于以下两个方面:

a = [{'id': 1, 'name': 'one'}, {'id': 2, 'name': 'two'}, {'id': 3, 'name': 'three'}]
b = [3, 1, 2]

res = []

for index in b:
    for player in a:
        if index == player['id']:
            res.append(player)

print(res)

2 个答案:

答案 0 :(得分:3)

sorted(a, key=lambda d: b.index(d['id']))

答案 1 :(得分:2)

尝试一下:

>>> a = [{'id': 1, 'name': 'one'}, {'id':2, 'name': 'two'}, {'id': 3, 'name': 'three'}]
>>> b = [3,1,2]
>>> sorted(a, key= lambda x: l.index(x['id']))
[{'id': 3, 'name': 'three'}, {'id': 1, 'name': 'one'}, {'id': 2, 'name': 'two'}]