in

Sorting Python Dictionaries Like a Pro: The Ultimate Guide

Dictionaries are one of Python‘s most versatile data structures. As a fellow coding geek, you know dictionaries allow us to store data in easy-to-access key-value pairs.

But unlike sequences like lists and tuples, dictionaries are unordered by default. So how do we sort dictionary contents?

Well, not to worry my friend! In this comprehensive guide, I‘ll share all my tricks as a data analyst for sorting dictionaries in Python.

By the end, you‘ll be sorting dicts like a pro!

A Quick Refresher on Python Dictionaries

Let‘s kick things off with a quick recap of Python dictionary basics:

  • Dictionaries use keys to lookup values, like a real world dictionary maps words to definitions.

  • Keys must be unique, while values can be any Python datatype – strings, numbers, lists, even other dicts!

  • Dictionaries are unordered, meaning there‘s no natural sequence associated with the key-value pairs.

Here‘s an example dictionary:

person = {
  "name": "Mary",
  "age": 32,
  "address": "14 Main Street"
}

We can access values easily by key:

print(person["name"]) # Prints "Mary"
print(person["age"]) # Prints 32

Now that we‘re clear on basics, let‘s get sorting!

Sorting by Key

To sort a dictionary by key, we need to:

  1. Extract the keys
  2. Sort the keys
  3. Reconstruct dictionary with sorted keys

Let‘s see this in action. Say we have a dictionary of desserts:

desserts = {
  "ice cream": 5,
  "apple pie": 4,
  "cheesecake": 3,
  "chocolate cake": 2,
  "cherry tart": 1
}

Step 1: Extract the Keys

Use the .keys() dictionary method to extract keys as a list:

keys = desserts.keys() 

print(keys)
# dict_keys([‘ice cream‘, ‘apple pie‘, ‘cheesecake‘, ...])

Step 2: Sort the Keys

Apply Python‘s built-in sorted() function to get a sorted list:

sorted_keys = sorted(keys)

print(sorted_keys) 
# [‘apple pie‘, ‘cheesecake‘, ‘cherry tart‘, ... ]

Step 3: Reconstruct Dictionary

Loop through the sorted keys and assign original values:

sorted_dict = {}

for key in sorted_keys:
  sorted_dict[key] = desserts[key]

print(sorted_dict)

# {‘apple pie‘: 4, 
#  ‘cheesecake‘: 3,
#  ‘cherry tart‘: 1,
#  ...
#  ‘ice cream‘: 5}  

We can also use a dictionary comprehension to condense Steps 2 and 3:

sorted_dict = {key: desserts[key] for key in sorted_keys}

And there we have it – dictionary sorted by key, in just 3 easy steps!

Sorting by Value

What if we want to sort the dictionary by value instead of key?

The process is similar, but we‘ll use .items() to get key-value pairs:

Step 1: Extract Items as Tuples

Use .items() to get a list of (key, value) tuples:

items = desserts.items()

print(items)
# dict_items([(‘ice cream‘, 5), 
#             (‘apple pie‘, 4), ...])

Step 2: Sort by Value

Pass a key function to sorted() to extract just the value:

sorted_items = sorted(items, key=lambda x: x[1]) 

print(sorted_items)
# [(‘cherry tart‘, 1),  
#  (‘chocolate cake‘, 2), 
#  (‘cheesecake‘, 3), ...])

The lambda x: x[1] function returns the value in each tuple.

Step 3: Reconstruct Dictionary

Build new dict from sorted list:

sorted_dict = {}

for key, value in sorted_items:
  sorted_dict[key] = value

print(sorted_dict)
# {‘cherry tart‘: 1, 
#  ‘chocolate cake‘: 2,
#  ‘cheesecake‘: 3,
#  ...
# ‘ice cream‘: 5}

And again, we can use a dict comprehension to condense Steps 2 and 3.

To sort descending, just add reverse=True to sorted().

Key Points to Remember

Here are some key pointers as you work with sorting dictionaries in Python:

  • Use dict.keys() and dict.items() to get keys/pairs as lists.
  • Pass the lists to sorted() to sort alphabetically.
  • Customize ordering by passing key and reverse arguments.
  • Build a new dict by looping or using a dict comprehension.
  • Sorting doesn‘t change the original dict, it returns a new one!

When Would You Want to Sort a Dictionary?

Here are some of the most common use cases:

  • Displaying dictionary data to users in a sorted order for readability.
  • Serializing a dictionary to JSON with sorted keys for consistent output.
  • Iterating through a dictionary in a sorted sequence for your program‘s logic.
  • Sorting dictionary entries for fast lookup later using binary search.

As you can see, sorting dictionaries can be super helpful as you work with key-value data!

Alternative Options for Ordered Data

Dictionaries themselves are unordered in Python. If you need to maintain element ordering, here are some options:

  • OrderedDict from collections – remembers insertion order of keys
  • List of tuples – provides control over ordering
  • Pandas DataFramesort_values() and sort_index() methods
  • Numpy array – fast multi-dimensional arrays that can be sorted

For most cases, sorting a regular dict works great. But it‘s good to know these alternatives!

Case Study: Analyzing Student Marks

Let‘s look at a real-world example of sorting dictionaries. Say we have some exam marks for students:

student_marks = {
  "Randy": 78,
  "Stan": 89,
  "Kyle": 64,
  "Kenny": 95,
  "Butters": 82,
  "Token": 77
}

As their data analyst, we may want to:

  • See the highest and lowest scorers
  • Calculate statics like mean, median, standard deviation
  • Rank students by performance

To make this easier, let‘s sort the dictionary by mark:

sorted_marks = sorted(student_marks.items(), key=lambda x: x[1], reverse=True)

print(sorted_marks)
# [(‘Kenny‘, 95),
#  (‘Stan‘, 89),  
#  (‘Butters‘, 82),
#  (‘Randy‘, 78),
#  (‘Token‘, 77), 
#  (‘Kyle‘, 64)]

Now we can easily find highest and lowest scores. Calculating statistics is also simpler with sorted data.

We could even print a rank table:

Rank  Name    Marks
1     Kenny   95
2     Stan    89
3     Butters 82 
4     Randy   78
5     Token   77
6     Kyle    64

Sorting facilitated deeper analysis!

Final Thoughts

We‘ve covered a ton of ground on sorting dictionaries in Python!

Here are the key takeaways:

  • Get keys with .keys() and key-value pairs with .items().
  • Use sorted() to sort extracted lists alphabetically or by value.
  • Customize ordering with key and reverse arguments.
  • Reconstruct a sorted dictionary from the sorted list.
  • Sorting is useful for ordered display, analysis, lookups, etc.

Dictionary sorting is a valuable tool for any Python programmer. I hope these tips help you become a dictionary sorting pro!

Let me know if you have any other questions. Happy coding!

AlexisKestler

Written by Alexis Kestler

A female web designer and programmer - Now is a 36-year IT professional with over 15 years of experience living in NorCal. I enjoy keeping my feet wet in the world of technology through reading, working, and researching topics that pique my interest.