def sort_n_rank(rows, stat, highest_is_first=True):
    """Helper to sort and rank the rows for the given stat."""
    # sort rows
    rows = sorted(rows, key=lambda x: (float(x.get(stat)), float(x.get('k/d')), x.get('player'), x.get('team')), reverse=highest_is_first)

    # add rank to each row
    val, rank = 0, 0
    for i, row in enumerate(rows):
         if i == 0 or val != row[stat]:
             row['rank'] = rank = i+1
             val = row[stat]
         else:
             row['rank'] = rank
    return rows