0

I am trying to write a grouped namedtuple to a CSV, where each line is each name The namedtuple is like this: [FullIndividualResults(Position='48', Cat='B', Name='John Smith ', Team='Team 1', Points='10') My intended output in the CSV would be:

Cat,Name,Team,Points
B,John Smith,Team 1,10

I have this code:

fields = ("Position", "Cat", "Name", "Team", "Points")  # setting the fields for the namedtuple
FullIndividualResults = namedtuple('FullIndividualResults', fields)  # creating namedtuple

FinalOutput = sorted("Individual Series Results Cumulative.csv"),
                     key=lambda k: k.Name)  # grouping namedtuple by name


# Function to write namedtuple to a new CSV
def write_data(data_in, data_out):
    out = []  # create a list for the the namedtuples

    def return_names(x):  # function to return the value of the team in the group
        return x.Name

    for name, group in groupby(data_in, return_names):  # creating a group of namedtuples where each group is a different team
        group = list(group)  # creating a list of clubs, grouped so there is not any repeats
        d = {'Cat': Cat, 'Name': Name, 'Team': Team, 'Points': sum(int(i.Points) for i in group)}
        # defining a dictionary for each team where team is the value Team,
        # points is the sum of all the points of riders in that group,
        # AvgPoints is the avg value of points and NumOfRiders is number of items in the group
        out.append(d)  # adding the above dictionary to the list out
        with open(data_out, 'w', newline='') as csv_file:  # writing data to a new csv
            fieldnames = ['Cat', 'Name', 'Team', 'Points']  # setting row headers of output csv
            writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
            writer.writeheader()
            for row in out:  # for every value in the list out a new row in the csv will be written
                writer.writerow(row)

However, this will return a NameError for Cat, Name, and Team, as they are not defined but I am not sure how I would define these.

PythonIsBae
  • 368
  • 3
  • 10
  • The line `FinalOutput = sorted("..."` is not doing what you think. It is taking the string of your filename and attempting to sort each character as if it is a named tuple. To sort by name you need to first read it into a list. – Martin Evans Jun 12 '20 at 13:12
  • Sorry I didn't include my full code, each row in a csv is created into a namedtuple, grouped by team and sorted alphabetically by team. It does work as I intend as if I omit Cat and Team using `Name` as `'Name': return_names(x)` it works, I just can't include Cat and Team – PythonIsBae Jun 15 '20 at 12:49

0 Answers0