Explain Codes LogoExplain Codes Logo

How do I sort a dictionary by value?

python
sorting
dictionaries
dataframe
Anton ShumikhinbyAnton Shumikhin·Aug 28, 2024
TLDR

Here you go. Here's how to sort a dictionary by value in Python:

# Dictionary sorting, faster than a caffeinated coder on caffeine! sorted_dict = dict(sorted(d.items(), key=lambda item: item[1]))

Just replace d with your dictionary. If you're into the normal ascending order vibe, keep it as is. More of an upside-down or descending fan? No problem, just add reverse=True:

# Ascending order (like unravelling a yarn of code) sorted_dict = dict(sorted({'apple': 4, 'banana': 2, 'cherry': 3}.items(), key=lambda item: item[1])) # Descending order (like diving into a pool of functions) sorted_dict_desc = dict(sorted({'apple': 4, 'banana': 2, 'cherry': 3}.items(), key=lambda item: item[1], reverse=True))

Sorted, literally!

Sorting Python dictionaries: under the hood

Given the unordered nature of Python dictionaries (until 3.6), sorting them into a meaningful order can feel like sorting a room full of hyperactive puppies. But hang tight! Let's untangle the leash here.

The operator way to sort

If lambdas give you headache, Python operator module is your analgesic:

import operator # Python's operator module in disguise. Oops, given away the secret identity! sorted_items = sorted(d.items(), key=operator.itemgetter(1))

Python's vintage way of sorting dictionaries

Prior to Python 3.7, attempting to sort a dictionary was like trying to herd cats. It refused to stay put, that's when collections.OrderedDict came to the rescue:

import collections # It's like sorting your old pics...but these are key-value pairs...and not actually old. sorted_dict = collections.OrderedDict(sorted(d.items(), key=lambda item: item[1]))

The sorted function Deja vu

Ever used sorted()? That's your ticket to dictionary sorting. It's like your personal butler, catering to your sorting whims with three parameters:

  • iterable: The sequence (dressed in dashing tuple attire AND bubble-wrapped in dict.items())
  • key: Your ordering principle, cleverly masked as a function (No, not Batman, it's just a lambda function in a key costume 🦸‍♀️).
  • reverse: The switch from ascending to descending is a True away.

The sorting infinity stones

Python's sorting algorithm carries some hidden gems that include:

  • A flip switch (reverse=True) to tilt the world from ascending to descending.
  • The ability to sort by word count like a boss:
from collections import Counter # Now, tell me python, which word did they use the most? word_counts = Counter(your_text.split()) sorted_by_occurrence = sorted(word_counts.items(), key=lambda item: item[1], reverse=True)

Mastering the sorting jutsu

Sorting in Python is an art. To be a true Naruto of sorting, hone these skills:

Sorting you can trust: by keys

If keys are your thing, voila! Just omit the key function:

sorted_by_key = dict(sorted(d.items()))

Sorting you can flip: descending order

Like flipping pancakes? You can flip your dictionary order with reverse=True:

# And gravity does its thing... sorted_desc = dict(sorted(d.items(), key=lambda item: item[1], reverse=True))

Sorting you can customize: composite values

Fun fact: Python also sorts tuples or lists like a charm:

# Pairing and sorting, we're basically matchmaking here sorted_comp = dict(sorted(d.items(), key=lambda item: (item[1][0], item[1][1])))

The sorting wok of fire

Beware of the fire-spitting dragons while sorting:

  • Memory-intensive operations in large datasets. Fight fire with fire by using generators or sorting in chunks.
  • Sorting complex data types requires a bit of ingenuity and customized keys.
  • Python's sort is stable: identical items retain their order. But remember, with great power comes great stability.

Sorting with swag: more scenarios, more sorting

Sorting custom objects

Every wondered if dictionaries can store custom objects? Keep wondering...because yes, they can!

# Unleashing the object sorter sorted_custom = dict(sorted(d.items(), key=lambda item: item[1].custom_attribute))

Sorting with a safety net for nulls

Fear no more None values! The custom key function is here to clear your path:

# Clearing the None hurdles in style sorted_handle_none = dict(sorted(d.items(), key=lambda item: (item[1] is not None, item[1])))

Bringing your SQL skills to Python sorting

ORDER BY your wishes, here's Python mimicking SQL like style:

# SQL in Python clothing. Clever, eh? sorted_like_db = dict(sorted(d.items(), key=lambda item: (item[1]['age'], item[1]['name'])))