Search code examples
pythonpython-3.xcolumnsorting

How to sort items by column from a text file in python


I have the following items in a text file with names of cities and there quarter revenues:

 Atlanta   40 50 23 18
 Denver    56 78 34 11
 Miami     40 34 18 30
 Orlando   55 67 23 11
 Memphis   44 23 56 11
 Boston    55 67 33 23
 Tampa     45 67 54 77

I am having issues with sorting the quarter revenues in the list. My current program looks like this.

with open('revenue.txt', 'r') as f:
text = [line.split() for line in f]
print("{:<12}{:<14}{:>10}{:>9}".format("City", "Revenue", "Total", 
"Average"))
for a in text:
    city = a[0]
    revenue = [int(i) for i in a[1:5]]
    total = sum(revenue)
    avg = sum(revenue)/len(revenue)
    print("{:<12}{}{:>6}{:>9.2f}".format(city, revenue, total, avg))

print("\n""Sort the cities by their Quarter 1 revenues.")

print("\n""Sort the cities by their Quarter 3 revenues.")

print("\n""Sort the cities by their total revenues.")

I am trying to figure out how I can sort 1st quarter, 3rd quarter,and total columns and then print the city that is associated with them. For example:

Sort the cities by their Quarter 1 revenues
['Miami','Atlanta','Memphis','Tampa','Boston','Orlando','Denver']
#  [40,40,44,45,55,55,56]

Any help will be appreciated.


Solution

  • I'd use a dictionary along with a list to increase readability in your sort and how usable your code is. I went ahead and implemented a function for printing the table (because you do it several times inside your function). I also added a list of dictionaries as your new dataset. Then I used the function sorted to build your newly organized list.

    with open('revenue.txt', 'r') as f:
        def print_table(data):
            for value in data:
                print("{city:<12}{revenue}{total:>6}{avg:>9.2f}".format(**value))
        text = [line.split() for line in f]
        data = []
        for a in text:
            revenue = [int(i) for i in a[1:5]]
            data.append({
                'city': a[0],
                'revenue': revenue,
                'total' : sum(revenue),
                'avg' : sum(revenue)/len(revenue)
            })
        print("\n""Original data set.")
        print_table(data)
    
        print("\n""Sort the cities by their Quarter 1 revenues.")
        print_table(sorted(data,key=lambda a: a['revenue'][0]))   
    
        print("\n""Sort the cities by their Quarter 3 revenues.")
        print_table(sorted(data,key=lambda a: a['revenue'][2]))   
    
        print("\n""Sort the cities by their total revenues.")
        print_table(sorted(data,key=lambda a: a['total']))