Skip to content Skip to sidebar Skip to footer

Getting Specific Line And Value With Python Dictreader

I have a csv file and am trying to get one specific value on, say, line 20, column 3. But so far, all I managed is to display all values on column 3 (here called 'name'). Here is m

Solution 1:

Naive solution:

  target_row = 5for num, line in enumerate(d):
      ifnum== target_row:
          print line["name"]
          break

I removed the intermediate variable score.

Note that this is non-optimal, as you iterate until you reach the desired row, but I don't know if there is random access to lines in the DictReader.

Solution 2:

Skipping ahead to the desired line, just as in the other answer, but with slicing on the CSV-reading iterator instead of a manual loop:

import csv, itertools
rownum = 20
colname = "name"
line = itertools.islice(d, rownum - 1, rownum).next()
score = line[colname]

(Not the most beautiful code, I know, but that's just to illustrate the point.)

Solution 3:

In short, convert the output of csv.DictReader to a list format and access the values with index.

Note: The value returned when you access by index will be an object with keys corresponding to the column names in the CSV file


Use Case:

I had a similar need. I only wanted to read a subset of rows, say lines 10-15 from a total of 100 lines.

A simple solution that worked was to convert it into list:

# Observe that I am converting the output of DictReader into a list format
lines = list(csv.DictReader(open('somefile.csv', 'r')))

# Once I have the list of objects, I can simple access it with rangefor i inrange(10, 15):
    line = lines[i]
    # If you want to read the value of a specific columnprint line['column_name']

Hope this helps.

Solution 4:

if you only know the column number and the line number you can do like this:

TheRow = 2# Note that row 1 is the header row
TheColumn = 2# first column == 0for row in d:
    if d.line_num == TheRow:
        print("row %s: %s" % (str(d.line_num), str(row) ) )
        print( row[d.fieldnames[TheColumn]] )

output:

row 2: {'t1': '12', 't2': '23', 't3': '31'}
31

Post a Comment for "Getting Specific Line And Value With Python Dictreader"