Sorting a dictionary based on the largest sum of array values
I know there are similar questions, but I cannot find an answer to my specific problem. Therefore, I have thousands of records that have the following format:
geneA 6 0 0
geneB 5 0 0
geneC 4 0 0
geneD 3 0 0
geneE 0 6 1
The above is an example of the output I am getting, but I want the data to be ordered in such a way that the first row has the largest sum of the values ββof that array (otherwise I want geneE to be the first in this release because it has the largest sum). In my dictionary, genes are keys, and a list of numbers is a value that creates key-value pairs. This is currently my code which prints in descending order the highest and lowest values ββaccording to the first column of numbers, not the amount I want.
for key,value in sorted(dictionary.items(),key=lambda i:i[1][0],reverse=True):
print key,dictionary[key][0],dictionary[key][1],dictionary[key][2]
I'm trying to figure out how to state in Python that I want it to be sorted based on the sum of the values ββof a list, not just the first value of the list. We are extremely grateful for any help! Thank.
source to share
I assume your dict is formatted something like this:
{'geneA' : [6,0,0] ,...}
This key function will correctly output the list sorted in the order you want:
>>> for key,value in sorted(dictionary.items(),key=lambda i:sum(i[1]),reverse=True):
print key,value
geneE [0, 6, 1]
geneA [6, 0, 0]
geneB [5, 0, 0]
geneC [4, 0, 0]
geneD [3, 0, 0]
source to share