zig
zig

Reputation: 69

read the second row of a csv file into a dict

i have a csv file that looks something like this:

username,permission,type,avtar
user1,op,member,goldilock
user2,guest
user3,guest

The 'type' and 'avtar' data is only in the second row (user1), for user2 and user3 this will be empty. What i am trying to achieve is get the type and avtar data from the second row and put that into a dict that would look like this:

{'type': 'member', 'avtar': 'goldilock'}

I tried to use the built-in csv.DictReader, i do not want to use panda for this. I can get all the contents of the csv file into a dict using the above module, but i do not knw how i can select a specific row and put them into a dict.

Following is the code that i have so far, is it possible to use DictReader module to achieve this at all? or there is another approach i should adopt?

import csv 
inputFile="test.csv"
with open(inputFile, "rb") as data:
    reader = csv.DictReader(data)
    for row in reader:
        print row['type']

Upvotes: 1

Views: 2805

Answers (1)

OneCricketeer
OneCricketeer

Reputation: 191738

If you only want one row, don't use a loop. Use the iterator

reader = csv.DictReader(data)
row2 = next(reader) 

Upvotes: 3

Related Questions