Getting a specific string and value using Python DictReader

I have a csv file and I'm trying to get one specific value, for example, in row 20, in column 3.

But so far I have managed to display all the values ​​in column 3 (here called "name").

Here is my Python code

d = DictReader(r.csv().split('\n'))
for line in d:
    score = line["name"]
    print score

How can I display and retrieve a value only for a specific row?

+3
source share
2 answers

Naive solution:

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

I deleted the intermediate variable score.

Please note that this is not optimal, as you repeat until you reach the desired line, but I do not know if there is any random access to the lines in DictReader.

+5
source

, , CSV :

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

( , , .)

+2

Source: https://habr.com/ru/post/1789521/


All Articles