Python Forum

Full Version: csv.reader vs csv.dictReader
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm having a lot of difficulty understanding the difference between csv.reader and csv.dictReader. The Python docs didn't shed much light for me on this point...
Basically when would I elect to use csv.reader and where is csv.dictReader the better choice (I feel the answer must relate to fieldnames?

So my questions are :
1) what is the difference between the two methods?
2) my code reprints the fieldnames when I use csv.dictReader
3) rightnow my fieldnames are in my csv file...how do I attach them to print with csv methods
(for example with csv.dictWriter it is fieldnames=['id','a','b','c','d']; somefile = csv.DictWriter(someotherfile, fieldnames=fieldnames];somefile.writeheader() what is csv.reader/csv.dictReader alternative?

here is my csv:
Output:
id-a-b-c-d 1-foo-1-2-0 2-bar-10-20-0 3-moo-2-3-0
here is my code:
opened_file = open('foo0.csv')
print(opened_file.read())#this prints out fine

with open('foo0.csv') as openme:
#also, how do I implement fieldnames with csv.reader OR csv.dictReader (the docs show me how to do this with csv.dictWriter only)
	readme = csv.DictReader(openme, delimiter='-')#this refuses to work...it simply reprint my 'fieldnames'
	for x in readme:
		print(' '.join(x))
my output:
Output:
id-a-b-c-d 1-foo-1-2-0 2-bar-10-20-0 3-moo-2-3-0 id a b c d id a b c d id a b c d
In simple terms csv.reader and csv.writer work with list/tuple, while csv.DictReader and csv.DictWriter work with dict.
csv.DictReader and csv.DictWriter take additional argument fieldnames that are used as dict keys.
scores.csv
Output:
id,name,score 1,John,10 2,Annie,25 3,Jane,15
import csv

with open('scores.csv') as f:
    rdr = csv.reader(f)
    for line in rdr:
        print(type(line))
        print(line)
        
print ('\n\nusing DictReader \n')

with open('scores.csv') as f:
    rdr = csv.DictReader(f)
    print 'fieldnames:', rdr.fieldnames
    for line in rdr:
        print(type(line))
        print(line)
output

Output:
<type 'list'> ['id', 'name', 'score'] <type 'list'> ['1', 'John', '10'] <type 'list'> ['2', 'Annie', '25'] <type 'list'> ['3', 'Jane', '15'] using DictReader fieldnames: ['id', 'name', 'score'] <type 'dict'> {'score': '10', 'id': '1', 'name': 'John'} <type 'dict'> {'score': '25', 'id': '2', 'name': 'Annie'} <type 'dict'> {'score': '15', 'id': '3', 'name': 'Jane'} >>>
(Mar-19-2018, 06:52 AM)mepyyeti Wrote: [ -> ]
readme = csv.DictReader(openme, delimiter='-')#this refuses to work...it simply reprint my 'fieldnames'

So the line above won't work b/c I'm missing fieldnames statement...the python docs aren't quite clear on this.

Also for a bare knuckles inventory system which is be better dictReader/Writer or Reader/Writer. If those are your only options... I'm leaning toward the use of dictionaries only because I can use the 'column'/fieldnames names as keys...
(Mar-19-2018, 09:55 PM)mepyyeti Wrote: [ -> ]So the line above won't work b/c I'm missing fieldnames statement...the python docs aren't quite clear on this.
This is not True. Both with respect to working and documentation being not clear. From the docs
Quote:The fieldnames parameter is a sequence. If fieldnames is omitted, the values in the first row of file f will be used as the fieldnames. Regardless of how the fieldnames are determined, the ordered dictionary preserves their original ordering.

As to which one is better - I would not put it this way (better/worse). It depends on the particular setup and your preferences. I tend to prefer DictReader/DictWriter. However if your data comes from a database it will be list of tuples, so writer could be handy. On other hand you can easily turn list/tuple into dict usizng dict(zip(keys, values)) given you have the fieldnames as list/tuple (keys) and values as list too.