0

I am trying to sort a dictionary out in an ascending order by their values. The code seems to be working but the values are not sorted in the right way. I have tried to google around but I don't get why this isn't sorted correctly.

import sys
import argparse
import operator

def main (argv):
    parser = argparse.ArgumentParser(description='Sort out the model by the total energy score')
    parser.add_argument('infile', help='file to process')
    parser.add_argument('outfile', help='file to produce')
    args = parser.parse_args()
    values = {}
    energy =[]
    name = []

    with open(args.infile, "r") as f:
        file_in = f.readlines()[2:]
        for line in file_in:
            temp = line.split()
            if temp[0] == "SCORE:":
                ee = temp[1]
                nn = temp[32]
                energy.append(ee)
                name.append(nn)

    with open(args.outfile,"w+") as of:
        values = dict(zip(name, energy))
        results = sorted(values.items(), key=operator.itemgetter(1), reverse=False)
        for k,v in results:
            print(k,v)
        of.write(k+'\n'
if __name__ == "__main__":
    main(sys.argv)  

The output:

('aa4mwf28_0001_0005', '-0.720')
('aa4mwf28_0001_0032', '-2.466')
('aa4mwf28_0001_0002', '-21.234')
('aa4mwf28_0001_0010', '-21.554')
('aa4mwf28_0001_0004', '-22.366')
('aa4mwf28_0001_0033', '-22.725')
('aa4mwf28_0001_0008', '-24.567')
('aa4mwf28_0001_0027', '-30.690')
('aa4mwf28_0001_0019', '-30.842')
('aa4mwf28_0001_0052', '-4.480')
('aa4mwf28_0001_0065', '-40.598')
('aa4mwf28_0001_0022', '-49.729')
('aa4mwf28_0001_0075', '-56.418')
('aa4mwf28_0001_0014', '-62.785')
('aa4mwf28_0001_0040', '-67.777')
('aa4mwf28_0001_0015', '10.168')
('aa4mwf28_0001_0070', '109.161')
('aa4mwf28_0001_0074', '1174.320')
('aa4mwf28_0001_0057', '1228.966')
('aa4mwf28_0001_0062', '13.605')
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Loki
  • 99
  • 6
  • You are sorting strings, not numbers. Strings are ordered *lexicographically*, so comparing character by character. `1` is sorted before `2`, regardless of what other digits follow. – Martijn Pieters Oct 13 '17 at 15:26
  • `key=lambda kv: float(kv[1])` would produce a sort based on the floating point conversion of the string. – Martijn Pieters Oct 13 '17 at 15:28

0 Answers0