Python3 Sort Dict by Value or Object Attributes

Mar 28, 2020

Sort by Value

data = {    1: 'Apple',    2: 'Dragon Fruid',    3: 'Banana',    5: 'Eggfruit',    4: 'Cherry'}# {1: 'Apple', 3: 'Banana', 4: 'Cherry', 2: 'Dragon Fruid', 5: 'Eggfruit'}data = dict(sorted(data.items(), key=lambda x: x[1])) # , reverse=True

Sort by Object Attributes

data = {    1: {'name': 'Apple', 'total': 100},    2: {'name': 'Banana', 'total': 900},    3: {'name': 'Cherry', 'total': 50}}# {3: {'name': 'Cherry', 'total': 50}, 1: {'name': 'Apple', 'total': 100}, 2: {'name': 'Banana', 'total': 900}}data = dict(sorted(data.items(), key=lambda x: x[1]['total'])) # reverse=True

❤️ 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.