[Tutor] Read a random record in dictionary object from csv module reader?

Kent Johnson kent37 at tds.net
Mon Oct 6 21:55:32 CEST 2008


On Mon, Oct 6, 2008 at 3:32 PM, xbmuncher <xboxmuncher at gmail.com> wrote:
> import csv
> reader = csv.DictReader(open("test_csv.csv", "r"))

You should open the file with mode 'rb'

> reader is not an actual dictionary from my understanding.. so I don't know
> how to access properties like the 'total items' in the dictionary
> I want to be able to extract a random dictionary entry from the csv file,
> how can I do this by using the csv reader module? If I can't, then show me a
> better way to do it then..
>

reader is not a dictionary at all; it is a factory for dictionaries.
It produces a new dict for each line in the input file. Given your
code above, and assuming that the first line of the CSV file contains
field names, you can say
for d in reader:
  # d is a dict mapping field names to value for one line in the input file.

If you want all the items in a list, you could say
all_items = list(reader)

Then len(all_items) is the number of items in the dictionary and
random.choice(all_items) would give a randomly selected item dict.

Kent


More information about the Tutor mailing list