-1

I have an array of dicts, [{'id': 1, 'name': 'one'}, {'id':2, 'name': 'two'}, {'id': 3, 'name': 'three'}] and the array with sorted ids [3, 1, 2]

The expected result is

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

What is the best way to do this?

My code is based on two for:

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)
Headmaster
  • 2,008
  • 4
  • 24
  • 51

2 Answers2

3
sorted(a, key=lambda d: b.index(d['id']))
Alex Hall
  • 34,833
  • 5
  • 57
  • 89
2

Try this :

>>> 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'}]
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56