Reputation: 283
I know there are similar questions out there, but I can't find an answer to my specific problem. So I have thousands of entries which are of 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 a sample of the output that I am getting, but what I want is for the data to be ordered such that the first line has the largest sum of it's array values (aka I want geneE to be the first one in this output because it has the largest sum). In my dictionary the genes are the keys and the list of numbers is the value, creating key-value pairs. Currently this is my code that prints out in descending order the largest to lowest values according to the first column of numbers, rather than the sum which is what 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 am struggling to figure out how to state in Python that I want it sorted based on the sum of the list values rather than just the first value of the list. Any help would be enormously appreciated! Thank you.
Upvotes: 4
Views: 1734
Reputation: 6693
I'm assuming your dict is formatted something like this:
{'geneA' : [6,0,0] ,...}
This key function will properly 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]
Upvotes: 3