[sac-forum] Paul's Programming 4
- From: Paul Dickson <dickson@xxxxxxxxxxxxxxxxx>
- To: SAC Forum <sac-forum@xxxxxxxxxxxxx>
- Date: Sat, 26 Jun 2004 15:25:44 -0700
Here's a peek at where I'd like to take this:
>>> import csv
>>> db = {}
>>> file = open("sac72.txt","r")
>>> reader = csv.reader(file)
>>> header = reader.next()
>>> for record in reader:
... db[record[0].strip()] = record
...
>>> file.close()
>>> len(header[-1])
71
>>> header[-1].strip()
'NOTES'
>>> db["NGC 224"][-1].strip()
'Local Group;Andromeda Galaxy;nearest spiral'
>>> header[4:6]
['R.A. ', 'DEC. ']
>>> db["NGC 224"][4:6]
['00 42.7', '+41 16']
In this example, I imported the csv module, created an empty dictionary
(db = {}), then read the entire SAC Deep-Sky database into that dictionary
(the for loop).
The last field in the database is the NOTES field. It is supposed to be
71 characters and the len() function sgrees with it. When I peeked at
these values, I invoked the .strip() method to remove the padding spaces.
I don't need to do this for the RA and DEC values, they're already short
enough to print.
The dictionary, db, now holds the entire database. The text from the
first field of the database is the dictionary's key for that record and
the record is stored as a list. There's a minor problem in the above
code. The object names in the database have spaces added to help with
sorting (eg it's "NGC 224" above, and for NGC 1, it's "NGC 1").
To quickly summarize dictionaries, a dictionary is a generalized form of a
structure, but you don't need to know in advance what elements you'll
need.
>>> g = {}
>>> g["name"] = "John Smith"
>>> g["phone"] = "555-1111"
>>> g
{'phone': '555-1111', 'name': 'John Smith'}
>>> m = {"name":"Mary Johnson", "phone":"555-2222"}
>>> m
{'phone': '555-2222', 'name': 'Mary Johnson'}
You must create the dictionary before assigning keys and values to it.
>>> h["name"] = "Mike Smith"
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'h' is not defined
Dictionaries are unordered. To sort the above SAC database:
>>> keys = db.keys()
>>> keys[0:4]
['NGC 6747', 'NGC 5541', 'NGC 5939', 'NGC 5546']
>>> keys.sort()
>>> keys[0:4]
['3C 48', '3C 147', '3C 249.1', '3C 273']
>>> for i in keys:
... db[i]
...
I only printed the first 4 entries of the "keys" list. I also didn't
include the dump of the SAC database.
This concludes my brief summary of Python data types. There are others
types and you can create your own, but I don't plan on covering them.
-Paul
Other related posts:
- » [sac-forum] Paul's Programming 4