How to Sort Dictionary Keys Alphabetically in Python

This code returns a list of dictionary keys sorted alphabetically, using a case-insensitive comparison while preserving the original insertion order for keys that are equal.

Easy Python 3.7+ Aug 9, 2026 Dictionaries & sets 11 views 0 copies

Python code

18 lines
Python 3.7+
data = {
    "banana": 3,
    "apple": 1,
    "Cherry": 5,
    "date": 2,
    "apple": 4,
    "Fig": 6,
    "banana": 2,
}

def sort_dict_keys_alphabetically(d):
    """Return a list of keys sorted alphabetically (case-insensitive), stable for duplicates."""
    return sorted(d.keys(), key=lambda k: k.lower())

if __name__ == "__main__":
    sorted_keys = sort_dict_keys_alphabetically(data)
    print("Original keys:", list(data.keys()))
    print("Sorted keys (case-insensitive, stable):", sorted_keys)

Output

stdout
Original keys: ['banana', 'apple', 'Cherry', 'date', 'apple', 'Fig', 'banana']
Sorted keys (case-insensitive, stable): ['apple', 'apple', 'banana', 'banana', 'Cherry', 'date', 'Fig']

How it works

The sorted() function returns a new list of keys, leaving the original dictionary untouched. The key parameter accepts a function that computes a sorting key for each item; using str.lower() makes the comparison case-insensitive so 'apple' and 'Apple' are treated as equal. Because Python's sort is stable, items with the same case-insensitive key keep their original relative order, which is why both 'apple' entries appear before the 'banana' entries that also share the same lowercase key. This method works with any dictionary, including those with string keys, and orders capital letters alongside lowercase ones naturally.

Common mistakes

  • Forgetting that dictionaries don't preserve order until Python 3.7+, so using older versions may give unpredictable results.
  • Not specifying a `key` function results in a case-sensitive sort, placing 'Cherry' before 'apple'.
  • Assuming `sorted()` sorts the dictionary in place; it actually returns a new list, so you must assign it to a variable.

Variations

  1. Use `key=str.lower` instead of a lambda for cleaner code.
  2. To sort by the values instead, use `sorted(data)` and then access values, or use `sorted(data.items(), key=lambda item: item[1])`.

Real-world use cases

  • Generating a sorted list of configuration keys for a user-facing settings panel where case should be ignored.
  • Sorting column names from a CSV header before displaying them in a table, ensuring a consistent order regardless of capitalization.
  • Creating a deterministic ordering of API response fields for logging or testing, ignoring uppercase differences.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.