def table(data, head): # data er en liste av lister med tre elementer t = "{:^30}|{:^25}|{:^10}|\n".format(head[0],head[1],head[2]) t += ("-"*len(t)+"\n") for k in data: t += ("{:^30}|{:^25}|{:^10}|\n".format(k[0],k[1], k[2])) return(t) def population(l): return l[2] def main(): with open('norway_municipalities_2017.csv') as f: data = [] f_iter = iter(f) # I assume the csv file will always have a heading head = f_iter.__next__().strip("\n").split(',') for l in f: # we get a list where 0 is the kommune name, 1 is what fylke it is in and 2 is the population ll = l.strip("\n").split(',') ll[2] = int(ll[2]) data.append(ll) data.sort() data.sort(key=population, reverse=True) print(table(data, head)) if __name__ == "__main__": main()