Pass dict.items() to the built-in sorted() function and wrap the result in dict(...)—such as sorted_dict = dict(sorted(my_dict.items()))—which returns a new dictionary with keys ordered in ascending order (preserving insertion order in Python 3.7+).
Basic Example
scores = {"charlie": 85, "alice": 92, "bob": 78}
# 1. Sort dictionary keys in ascending order
sorted_asc = dict(sorted(scores.items()))
print(sorted_asc)
# Output: {'alice': 92, 'bob': 78, 'charlie': 85}
# 2. Sort dictionary keys in descending order
sorted_desc = dict(sorted(scores.items(), reverse=True))
print(sorted_desc)
# Output: {'charlie': 85, 'bob': 78, 'alice': 92}
Key Details & Edge Cases
- Why
dict(sorted(d.items()))works: Callingd.items()yields(key, value)tuples. Because Python compares tuples lexicographically starting with index0(the key),sorted(d.items())sorts by keys automatically without needing a customkey=lambda—anddict(...)reconstructs a new dictionary in that exact sorted order (guaranteed by the Python language spec since Python 3.7). - Dictionaries cannot be sorted in place: Unlike
list.sort(), Pythondictobjects have no.sort()method.dict(sorted(...))always creates a new dictionary; reassignmy_dict = dict(sorted(my_dict.items()))if you want to replace the original reference. - Case-insensitive string key sorting: By default, uppercase ASCII letters sort before lowercase letters (
"Zebra" < "apple"). Pass akey=function targetingitem[0](the key) to normalize case:users = {"bob": 1, "Alice": 2, "charlie": 3} case_insensitive = dict(sorted(users.items(), key=lambda item: item[0].lower())) # Output: {'Alice': 2, 'bob': 1, 'charlie': 3} - Sorting numeric keys stored as strings (e.g.,
"10"vs."2"): String keys sort lexicographically ("10"comes before"2"). Cast the key tointorfloatinside thekey=function for natural numeric ordering:chapters = {"10": "Appendix", "2": "Setup", "1": "Intro"} numeric_sorted = dict(sorted(chapters.items(), key=lambda item: int(item[0]))) # Output: {'1': 'Intro', '2': 'Setup', '10': 'Appendix'} - Mixed incomparable key types (
TypeError): Python 3 raisesTypeError: '<' not supported between instances of 'str' and 'int'if a dictionary mixes incompatible key types (e.g.,intandstr). Normalize keys in thekey=function (e.g.,key=lambda item: str(item[0])) if mixed types are present.
Comparison of Dictionary Key-Sorting Approaches
| Approach | Syntax | Return Type | Time Complexity | Best Used When |
|---|---|---|---|---|
dict(sorted(d.items())) |
dict(sorted(d.items())) |
dict (sorted) |
$O(n \log n)$ | Standard ascending or descending (reverse=True) key sort. |
Custom key= function |
dict(sorted(d.items(), key=lambda x: x[0].lower())) |
dict (sorted) |
$O(n \log n)$ | Case-insensitive, numeric-string, or multi-criteria key sorting. |
Iterating sorted(d) |
for k in sorted(d): print(k, d[k]) |
list of keys |
$O(n \log n)$ | Looping over keys in sorted order without allocating a new dict. |
collections.OrderedDict |
OrderedDict(sorted(d.items())) |
OrderedDict |
$O(n \log n)$ | Legacy Python < 3.7 compatibility or needing .move_to_end() / order-sensitive ==. |
You must log in or register to comment.
