[Tutor] Reading a CSV file

David Rock david at graniteweb.com
Sat Jun 13 12:18:18 EDT 2020


* John Weller <john at johnweller.co.uk> [2020-06-13 15:59]:
> Many thanks to all who replied.  I hoped it would be something like a
> dictionary.  The docs say that a dictionary is a sequence of key pairs -
> key:value but it appears that the value can be several fields.  Is this the
> case?

No. Dictionaries are key:value pairs, but "value" can be any type of object.
For example, the "value" could be another dictionary, a list, etc; all
of which have the potential to hold multiple items, not just a single
value.

> This program is intended to run 24/7 getting data every 10 minutes and using
> it to control equipment dependent on whether it is day or night.  There will
> be a setup function and a loop function.  I assume I can put the first part
> to create the dictionary is setup and the call in the loop?

Yes, that's exactly how my example is being used in stuff I'm doing.
Load the data into a dictionary once and reference it later.  It's a lot
faster than repeatedly walking the file.  The only reason to do that
would be if the data you are reading from changes every time.  If it's a
static table, read it once and reference the dictionary instead.

Another thing you my find handy is the pretty print module (pprint).  As
a test, after you create your sun_times OrderedDict with the csv module,
try doing:

pprint.pprint(sun_times)

to get a solid understanding of the layout of the dictionary created by
the csv module.

-- 
David Rock
david at graniteweb.com


More information about the Tutor mailing list