0

I want to see what the keys of the reader dictionary are so I use the print(key) function. The result is all the lines of the dictionary. Why is that?

import csv
from sys import argv, exit

# Check if there are enough command-line arguments
if len(argv) != 3:
    print("missing comment-line argument")
    exit(1)
# Open the CSV file to read
with open(argv[1], "r") as csvfile:
    reader = csv.DictReader(csvfile)
#   Why don't the following lines print the keys but all the lines in the CSV file?
    for key in reader:
         print(key)

The result:

OrderedDict([('name', 'Alice'), ('AGATC', '2'), ('AATG', '8'), ('TATC', '3')])

OrderedDict([('name', 'Bob'), ('AGATC', '4'), ('AATG', '1'), ('TATC', '5')])

OrderedDict([('name', 'Charlie'), ('AGATC', '3'), ('AATG', '2'), ('TATC', '5')])

1 Answer 1

0

The simplest method would be to reread only the first line of the csv and split the string using the commas like this:

keys = csvfile.readline().split(",")
print(keys)

Hope this helps. If it does then please check the tickmark.

2
  • I think that you've just forced the first line of the CSV file to be the keys.
    – nmn
    Nov 25, 2020 at 13:19
  • They are supposed to be the keys
    – Vsjain
    Nov 25, 2020 at 13:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .