How do I alphabetize data in a txt file to a list

Solution 1:

It seems as though what you need to do is split each entry of the list into a tuple. One nice solution is to use the parse module. Here's a way to do it from scratch.

def sep(line):
    line = line.strip()
    parts = line.split(', ',maxsplit = 2)
    return tuple(parts[:2] + [eval(parts[2])])

output = list(map(sep,list1))

To include the the file reading in the code, we could proceed as follows.

def sep(line):
    line = line.strip()
    parts = line.split(', ',maxsplit = 2)
    return tuple(parts[:2] + [eval(parts[2])])

with open('list.txt','r') as f:
    output = list(map(sep,f.readlines()))
output.sort()

Solution 2:

Note that this solution assumes you convert the text file to a csv (just rename the ending). Here is an alternative implementation to get the last element as a tuple:

import csv, ast

output = []
with open('path/to/city_time.csv', newline='') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
        for row in spamreader:
            row = row[:2] + [",".join(row[2:])]
            output.append(row)


output = sorted(output)

for o in output:
    o[2] = ast.literal_eval(o[2].strip())

print(output)

Output:

[['Amsterdam', ' Sun', (8, 520)], ['Anchorage', ' Sat', (23, 52)], ['Ankara', ' Sun', (10, 52)], ['Athens', ' Sun', (9, 52)], ['Atlanta', ' Sun', (2, 52)], ['Auckland', ' Sun', (20, 52)], ['Barcelona', ' Sun', (8, 52)], ['Beirut', ' Sun', (9, 52)], ['Toronto', ' Sun', (2, 52)], ['Vancouver', ' Sun', (0, 52)], ['Vienna', ' Sun', (8, 52)], ['Warsaw', ' Sun', (8, 52)], ['Washington DC', ' Sun', (2, 52)], ['Winnipeg', ' Sun', (1, 52)], ['Zurich', ' Sun', (8, 52)]]