Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a dictionary with lists as values, according to an element from the list

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.

like image 668
jay Avatar asked Aug 01 '09 19:08

jay


People also ask

How do you sort a dictionary according to a list?

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.

How do you sort a dictionary by using values?

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.

Can dictionary have list as values?

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.

How do you sort a dictionary by value and then by key?

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.


1 Answers

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] 
like image 98
Ayman Hourieh Avatar answered Sep 24 '22 02:09

Ayman Hourieh