Sort by value, ascending

scores = {"sam": 88, "ana": 95, "leo": 72}
ordered = dict(sorted(scores.items(), key=lambda item: item[1]))
print(ordered)   # {"leo": 72, "sam": 88, "ana": 95}

The items() call gives key-value pairs, and item[1] tells sorted() to compare on the value rather than the key.

Sort by value, descending

ordered = dict(sorted(scores.items(), key=lambda item: item[1], reverse=True))
print(ordered)   # {"ana": 95, "sam": 88, "leo": 72}

Adding reverse=True flips the order so the highest value comes first.

Use operator.itemgetter for speed

from operator import itemgetter
ordered = dict(sorted(scores.items(), key=itemgetter(1)))

itemgetter(1) does the same job as the lambda and is a touch faster on large dictionaries.

Which method should you use?

  • lambda — the readable default that most Python code uses.
  • itemgetter — when you want a small performance edge on big data.
  • reverse=True — whenever you want the largest values first.

Frequently asked questions

Does sorting change the original dictionary?

No. sorted() builds a brand-new list of pairs, and wrapping it in dict() makes a new dictionary, so your original is untouched.

Will the sorted order stick?

Yes. Since Python 3.7, dictionaries remember insertion order, so the new dictionary keeps the sorted sequence you gave it.

New to lambdas and key functions? Our free Python course explains them step by step.