Parker Johnson
Parker Johnson

Reputation: 19

CSV Survey results - python

I have a CSV with several questions, each question can have multiple answers (like survey results). Each question also has a corresponding question ID. At the end of my program I want to print the unique questions followed by each answer to only that question. I have tried messing with pandas and the CSV module and still can’t get it to print only the one unique question, followed by the corresponding survey results. Any pointers would be appreciated.

Say the below is my CSV file:

36,What is your favorite color?,Blue

24,What is your favorite food?,Tacos

36,What is your favorite color?,Red

12,What do you do for work?,Teacher

36,What is your favorite color?,Orange

24,What is your favoirte food?,Pizza

I just want to print out each unique question with its associated answers like this:

What is your favorite color?

Blue

Red

Orange

What is your favorite food?

Tacos

Pizza

What do you do for work?

Teacher

Upvotes: 0

Views: 272

Answers (1)

Freddy Mcloughlan
Freddy Mcloughlan

Reputation: 4496

You can iterate over each line, and store the answers in a dictionary with the ID as the key. Then you can print the dictionaries out iteratively, and '\n'.join all your answers together.

import csv

# Where to store your questions and answers
questions = {}

with open('data.csv', 'r') as r:
    reader = csv.reader(r)
    # Iterate over each csv entry
    for line in reader:
        # If you have not already seen this ID before
        if line[0] not in questions:
            # Create a new dictionary at that ID in questions
            questions[line[0]] = {'question': line[1],
                                  'answers': [line[2]]}
        else:
            # Otherwise just append to the answers
            questions[line[0]]['answers'].append(line[2])

for d in questions.values():
    print(d['question'])
    print('\n'.join(d['answers']))
    print('\n')

str.join()

Your output is

What is your favorite color?
Blue
Red
Orange


What is your favorite food?
Tacos
Pizza


What do you do for work?
Teacher

Make sure there are no blank lines in your csv

Your questions dict will look like:

{'12': {'answers': ['Teacher'], 'question': 'What do you do for work?'},
 '24': {'answers': ['Tacos', 'Pizza'],
        'question': 'What is your favorite food?'},
 '36': {'answers': ['Blue', 'Red', 'Orange'],
        'question': 'What is your favorite color?'}}

Upvotes: 1

Related Questions