snlonline
snlonline

Reputation: 47

Grouping Items Python

Let's say I have multiple unknown number of strings in a file. Every string is written in a new line. eg.

John, Task = Coding Challenge, Status = Not Completed

Kevin, Task = Compile, Status = Completed

John, Task = Fix Bug, Status = Completed

...etc

Exactly in this format,nevermind the spacing between lines its for readability

We don't know how many times John or Kevin will show up in this file. I want to group every single line according to their names, and provide the info in a user friendly manner. eg.

name = John

no. of tasks = 2

completed tasks = 1

etc...

Fairly new to programming, reason there's no code is because I don't even know where to start, I Understand basic Python (opening the text file, and iterating through the file). It is the next steps that follow after. Asking for steps and guidance really but a solution of the above example is also very much appreciated.

Upvotes: 0

Views: 48

Answers (1)

Rakesh
Rakesh

Reputation: 82755

This is one approach using csv module to process the file and dict to store the data

Ex:

import csv

result = {}
with open(filename) as infile:
    reader = csv.reader(infile)
    for name, *line in reader:
        completed = 1 if line[-1].endswith("Completed") else 0
        if name not in result:
            result[name] = {'name': name, 'tasks': 1, 'completed_tasks': completed}
        else:
            result[name]['tasks'] += 1
            result[name]['completed_tasks'] += completed

print(list(result.values()))

Output:

[{'completed_tasks': 2, 'name': 'John', 'tasks': 2}, 
 {'completed_tasks': 1, 'name': 'Kevin', 'tasks': 1}]

Upvotes: 1

Related Questions