I want to sort a dictionary of lists, by third item in each list. It's easy enough sorting a dictionary by value when the value is just a single number or string, but this list thing has me baffled.
Example:
myDict = {'item1': [7, 1, 9], 'item2': [8, 2, 3], 'item3': [9, 3, 11] }
I want to be able to iterate through the dictionary in order of the third value in each list, in this case item2
, item1
then item3
.
To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function.
First, we use the sorted() function to order the values of the dictionary. We then loop through the sorted values, finding the keys for each value. We add these keys-value pairs in the sorted order into a new dictionary. Note: Sorting does not allow you to re-order the dictionary in-place.
It definitely can have a list and any object as value but the dictionary cannot have a list as key because the list is mutable data structure and keys cannot be mutable else of what use are they.
To sort a dictionary by value then the key we can easily use the lambda and sorted function. In this example, we can set this reverse flag order as true which means the value will be in descending order.
Here is one way to do this:
>>> sorted(myDict.items(), key=lambda e: e[1][2]) [('item2', [8, 2, 3]), ('item1', [7, 1, 9]), ('item3', [9, 3, 11])]
The key
argument of the sorted
function lets you derive a sorting key for each element of the list.
To iterate over the keys/values in this list, you can use something like:
>>> for key, value in sorted(myDict.items(), key=lambda e: e[1][2]): ... print key, value ... item2 [8, 2, 3] item1 [7, 1, 9] item3 [9, 3, 11]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With