Search code examples
pythonsortingalphabetical

Sorting a list with 2 pieces of data alphabetically


After sortting out one of my sorting functions which sorts by score now I need to get it to accurately sort it by the first letter of the first name

The data in the file looks like this:

Amber 0
Cyan 1
Blue 2

I tried this:

with open("Scores.txt","r") as f:
    lines = sorted(f.readlines())
    print lines

This gives it out in a weird order. It starts with names beginning with A then moves onto names with R, then O.

My output would need to be like this:

Amber 0
Blue 2
Cyan 1

It is a relatively simple program and I am using Python 2.7

Any help would be amazing I can also provide any info on my program!


Solution

  • Try this,

    with open("Scores.txt","r") as f:
        lists = [line.rstrip().split() for line in f.readlines()]
        lists.sort()
        print(lists)
    
    # Output
    [['Amber', '0'], ['Blue', '2'], ['Cyan', '1']]