CSV Dictionary

Tim Chase python.list at tim.thechases.com
Mon Dec 29 11:29:33 EST 2014


On 2014-12-29 16:11, JC wrote:
> On Mon, 29 Dec 2014 09:47:23 -0600, Skip Montanaro wrote:
> 
> > On Mon, Dec 29, 2014 at 9:35 AM, JC <chalao.adda at gmail.com> wrote:
> >> How could I get the all the records?
> > 
> > This should work:
> > 
> > with open('x.csv','rb') as f:
> >     rdr = csv.DictReader(f,delimiter=',')
> >     rows = list(rdr)
> > 
> > You will be left with a list of dictionaries, one dict per row,
> > keyed by the values in the first row:
> > 
> >>>> import csv with open('x.csv','rb') as f:
> > ...     rdr = csv.DictReader(f,delimiter=',')
> > ...     rows = list(rdr)
>
> But now I see another problem. I cannot use the "rdr" object
> anymore. For example, I wanted to count the number of records. I
> used - count = sum(1 for r in rdr)
> It returned 0 records.

You exhausted that iterator.  Instead, if you put them all in the
list, just take len(rows)

Alternatively, if you want to have keyed O(1) access instead of O(N)
access to items in your CSV file, load them into a dictionary,
choosing the field you want to use for lookup:

  with open('x.csv', 'rb') as f:
    rdr = csv.DictReader(f) # delimiter defaults to ","
    d = dict(
      (row["userid"], row)
      for row in rdr
      )
  print("Loaded %i row(s)" % len(d))
  print("def at ghi: %r" % (d["def at ghi"]))

-tkc






More information about the Python-list mailing list