Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to sort data inside text file in accending order in python?

I have a text file containing number integer and string value pairs I want to sort them in ascending order but I am not getting it correct

**TextFile.txt **

87,Toronto
45,USA
45,PAKISTAN
33,India
38,Jerry
30,Tom
23,Jim
7,Love
38,Hate
30,Stress

My code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def sort_outputFiles():
    print('********* Sorting now **************')
    my_file = open("TextFile.txt", "r",encoding='utf-8')
    data = my_file.read()
    data_into_list = data.split("\n")
    my_file.close()
    score=[]
    links=[]
    for d in data_into_list:
        if d != '':
            s=d.split(',')
            score.append(s[0])
            links.append(s[1])
    n = len(score)
    for i in range(n):
        for j in range(0, n-i-1):
            if score[j] < score[j+1]:
                score[j], score[j+1] = score[j+1], score[j]
                links[j], links[j+1] = links[j+1], links[j]

    for l,s in zip(links,score):
        print(l," ",s)

My output

********* Sorting now **************
Toronto   87
Love   7
USA   45
PAKISTAN   45
Jerry   38
Hate   38
India   33
Tom   30
Stress   30
Jim   23

Expected output

********* Sorting now **************
Toronto   87
USA   45
PAKISTAN   45
Jerry   38
Hate   38
India   33
Tom   30
Stress   30
Jim   23
Love   7

having error at line 2 in out put it should be in last

>Solution :

You are comparing strings, not numbers.

In an dictionary (like, the physical book), the words are sorted by who has the "lowest" first letter, and if it’s a tie, we pick the lowest second letter, and so on. This is called lexicographical order.

So the string "aaaa" < "ab". Also, "1111" < "12"

To fix this, you have to convert the string to a number (using int(s[0]) instead of s[0] in the score.append function).

This will make 1111 > 12. Your code will give the correct result.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading