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.
Python code
18 linesdata = {
"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
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
- Use `key=str.lower` instead of a lambda for cleaner code.
- 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
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.