This article will show you how to sort a dictionary by the values it contains in the Python programming language. Code examples are included.
What is a Dictionary?
A dictionary is one of Pythons built in variable types for storing data. Dictionaries are similar to associative arrays or hash tables in other languages.
A dictionary contains a collection of values or objects. Unlike lists and arrays, rather than their values being stored at a specific index (the ordered position in the sequence of stored values), values in a dictionary are identified by a key. This key can be descriptive, telling you what the purpose of the value as well as being used to retrieve it.
Essentially, a dictionary is a collection of key/value pairs, where the value is retrieved by accessing the key.
In PHP, this functionality is provided using associative arrays. In JavaScript, objects can be used in a similar manner to dictionaries as they too can store and retrieve data as key/value pairs.
Dictionaries are Ordered and Can Be Changed
From Python version 3.7 and onwards, dictionaries are ordered – the entries in the dictionary will remain in the order they appeared in when the dictionary was defined or the values were added.
Dictionaries are also changeable – you can add, remove and alter the items within.
How to Sort a Python Dictionary by Value
The above means that dictionaries can be sorted by re-creating the dictionary with the items in a new order based on their value.
Note that this only works for Python 3.7 and above – you should always ensure you are running up-to-date versions of Python for security and compatibility.
Below, a dictionary containing quantities is defined, and then sorted by each quantity:
myDictionary = { "apples": 3, "bananas": 6, "oranges": 2, "limes": 9 } mySortedDictionary = { key: value for key, value in sorted(myDictionary.items(), key=lambda item: item[1]) } myReverseSortedDictionary = { key: value for key, value in sorted(myDictionary.items(), key=lambda item: item[1], reverse=True) }
The values of each new dictionary will now be in ascending and descending order.
So what’s going on here? The process is as follows:
- A new variable is declared to hold the sorted dictionary
- It is wrapped in {} (curly braces) – telling Python that the variable is a dictionary
- Within this new dictionary, the results of the sorted() function are enumerated as key/value pairs
- This enumeration goes through each item one by one and adds it to the wrapping dictionary
- This enumeration is necessary as sorted() returns a list, so it cannot be used to create a new dictionary directly
- The sorted() function sorts the values in the original dictionary, returning a list
- Note that you cannot sort a list of mixed string or numerical values – it’s one or the other
- The items() method of the original dictionary provides a list of the values from the original dictionary to be sorted
- The lambda expression is used to set the comparison key to the value of each entry in the dictionary
- A complete function can be used in its place for sorting by more complex methods
- An optional reverse parameter can be set to reverse the sort order
There’s much more to sorting in Python than simple sorts on numerical value – check out the official documentation for more.