The logic is straight forward for this.
- Read each line into a dictionary with the last name as the key
- Sort the keys
- Output the lines based on key (last name)
Try this code:
ss = '''
(fname3) (lname8) (12) (NY)
(fname2) (lname7) (34) (PA)
(fname4) (lname9) (11) (SF)
(fname1) (lname4) (40) (LA)
(fname5) (lname5) (5) (LV)
'''.strip()
with open ('names.txt','w') as f: f.write(ss) # write data file
#########################
with open('names.txt') as f:
lines = f.readlines()
d = {ln.split()[1]:ln.strip() for ln in lines} # use last name (col 2) as key
keysort = sorted([k for k in d]) # sort keys
for k in keysort:
print(d[k])
Output
(fname1) (lname4) (40) (LA)
(fname5) (lname5) (5) (LV)
(fname2) (lname7) (34) (PA)
(fname3) (lname8) (12) (NY)
(fname4) (lname9) (11) (SF)
Note that you can also split all the lines into arrays then sort the lines based on array index. The csv module can help with this.
CLICK HERE to find out more related problems solutions.