python
dictionary
iteration
sorted keys
programming

In Python, how do I iterate over a dictionary in sorted key order?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

If you want to iterate over a Python dictionary in sorted key order, the normal solution is to sort the keys at iteration time. The important distinction is that a dictionary preserves insertion order, not sorted order, so you must ask for sorting explicitly when you need it.

Use sorted on the Dictionary Keys

The shortest and most idiomatic form is:

python
1data = {"banana": 3, "apple": 5, "cherry": 2}
2
3for key in sorted(data):
4    print(key, data[key])

This works because iterating over a dictionary yields its keys, and sorted returns those keys in ascending order.

The output is:

text
apple 5
banana 3
cherry 2

For most code, this is the right answer. It is clear, easy to read, and avoids changing the dictionary itself.

Iterate Over Sorted Key-Value Pairs

If you prefer to work with key-value pairs directly, sort data.items().

python
1data = {"banana": 3, "apple": 5, "cherry": 2}
2
3for key, value in sorted(data.items()):
4    print(key, value)

This is convenient when you need both values and keys on each iteration and do not want to index back into the dictionary manually.

Be aware that sorting items() sorts primarily by key when the tuple structure is (key, value). That matches the common case here.

Use a Custom Sort Key When Needed

Sometimes “sorted” does not mean normal alphabetical order. Python lets you define the sort rule explicitly.

python
1data = {"banana": 3, "apple": 5, "cherry": 2}
2
3for key in sorted(data, key=len):
4    print(key, data[key])

This sorts by key length.

For case-insensitive sorting:

python
1data = {"Banana": 3, "apple": 5, "Cherry": 2}
2
3for key in sorted(data, key=str.lower):
4    print(key, data[key])

The general lesson is that the dictionary stays the same; only the traversal order changes.

Insertion Order Is Not Sorted Order

Since Python 3.7, standard dictionaries preserve insertion order. That sometimes causes confusion because people see stable output and assume the dictionary has become sorted.

python
1data = {}
2data["banana"] = 3
3data["apple"] = 5
4data["cherry"] = 2
5
6print(list(data))

This prints keys in the order they were inserted, not in alphabetical order. If you need sorted traversal, call sorted explicitly every time, or build a separate ordered view for display.

You Usually Do Not Need OrderedDict

For this specific task, OrderedDict is rarely necessary. OrderedDict is about preserving a chosen insertion sequence, while sorted(data) is about computing a temporary sorted iteration order.

python
1from collections import OrderedDict
2
3data = {"banana": 3, "apple": 5, "cherry": 2}
4sorted_view = OrderedDict((key, data[key]) for key in sorted(data))
5print(sorted_view)

That can be useful if you truly need a separately ordered mapping object, but for plain iteration it is often more machinery than you need.

When to Materialize a Sorted Structure

If you only need sorted output once, sorted(data) is enough. If you need sorted order repeatedly in performance-sensitive code, you may want to compute the sorted keys once and reuse them.

python
1sorted_keys = sorted(data)
2
3for key in sorted_keys:
4    print(key, data[key])

That avoids repeated sorting work when the dictionary is unchanged across many loops.

Common Pitfalls

  • Assuming dictionary insertion order means the dictionary is automatically sorted.
  • Sorting the keys but then forgetting to look up the corresponding values correctly.
  • Re-sorting the same large dictionary repeatedly when the key set has not changed.
  • Expecting sorted(data.items()) to sort by value when it actually sorts by key first.
  • Mutating the dictionary while iterating through a separately sorted key view.

Summary

  • Use for key in sorted(data): for the standard sorted-key iteration pattern.
  • Use sorted(data.items()) when you want sorted key-value pairs directly.
  • Add a key= function when “sorted” means something custom.
  • Dictionary insertion order is stable but not the same as sorted order.
  • Compute sorted keys once if you need the same ordering repeatedly.

Course illustration
Course illustration

All Rights Reserved.