[NEWB] Dictionary instantiation?

Matt_D matt.deboard at gmail.com
Fri Dec 7 03:05:16 EST 2007


Hello there, this is my first post to the list. Only been working with
Python for a few days. Basically a complete newbie to programming.

I'm working with csv module as an exercise to parse out a spreadsheet
I use for work.(I am an editor for a military journalism unit) Not
trying to do anything useful, just trying to manipulate the data.
Anyway, here's the code I've got so far:

import csv
import string
import os

#Open the appropriate .csv file
csv_file = csv.reader(open("D:\\Python25\\BNSR.csv"))

#Create blank dictionary to hold {[author]:[no. of stories]} data
story_per_author = {}

def author_to_dict(): #Function to add each author to the dictionary
once to get initial entry for that author
    for row in csv_file:
        author_count = row[-1]
        story_per_author[author_count] = 1

#Fetch author names
def rem_blank_authors(): #Function to remove entries with '' in the
AUTHOR field of the .csv
    csv_list = list(csv_file) #Convert the open file to list format
for e-z mode editing
    for row in csv_list:
        author_name = row[-1]
        if author_name == '': #Find entries where no author is listed
            csv_list.remove(row) #Remove those entries from the list

def assign_author_to_title(): #Assign an author to every title
    author_of_title = {}
    for row in csv_file:
        title = row[3]
        author = row[-1]
        author_of_title[title] = author


assign_author_to_title()
print author_of_title

--

Ok, the last two lines are kind of my "test the last function" test.
Now when I run these two lines I get the error:

Traceback (most recent call last):
  File "D:\Python25\Lib\SITE-P~1\PYTHON~1\pywin\framework
\scriptutils.py", line 310, in RunScript
    exec codeObject in __main__.__dict__
  File "D:\Python25\csv_read.py", line 33, in <module>
    print author_of_title
NameError: name 'author_of_title' is not defined

I am guessing that the author_of_title dict does not exist outside of
the function in which it is created? The concept of instantiation is
sort of foreign to me so I'm having some trouble predicting when it
happens.

If I call the assign_author_to_title function later, am I going to be
able to work with the author_of_title dictionary? Or is it best if I
create author_of_title outside of my function definitions?

Clearly I'm just stepping through my thought process right now,
creating functions as I see a need for them. I'm sure the code is
sloppy and terrible but please be gentle!



More information about the Python-list mailing list