Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Python: Sort a dictionary by value

📅 2009-Oct-26 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ dictionaries, python, sorting ⬩ 📚 Archive

A dictionary is not a data structure that can be sorted, either by key or by value. But there are times when we would like to iterate through a dictionary in the order of its values.

One way to do this is to create a list of key-value tuples from the dictionary and sort that based on the value:

# Dictionary that we want to iterate as if it was sorted by value
adict = {"nine": 9, "one": 1, "eight": 8, "three": 3}

import operator
kvals = sorted(adict.items(), key=operator.itemgetter(1))
# kvals: [('one', 1), ('three', 3), ('eight', 8), ('nine', 9)]

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧