Python Sort List of Objects Based on Another List of Keys

Sep 8, 2020
items = [  { 'id': 1, 'name': 'Apple'},  { 'id': 5, 'name': 'Orange'},  { 'id': 3, 'name': 'Banana'}]keys = [1, 3, 5]sorted_items = sorted(items, key = lambda x: keys.index(x['id']))

Results

[{'id': 1, 'name': 'Apple'}, {'id': 3, 'name': 'Banana'}, {'id': 5, 'name': 'Orange'}]

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.