[Tutor] Instantiating large numbers of objects? [lists and dictionaries]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 4 Feb 2002 18:24:22 -0800 (PST)


> > > list container.  In that case, we can use a more appropriate data
> > > structure, the dictionary:
> > >
> > > ###
> > > >>> people_dict = {}
> > > >>> for n in names:
> > > ...     people_dict[n] = Person(n)
> > > ...
> > > >>> people_dict['lisa'].sing()
> > > tra la la, my name is lisa
> > > ###
> >
> >  Again, the syntax is a little different than what I'm used to. I've
> > always never seen a dictionary done like this. Is it a case where the
> > syntax is different since its being added to a list?
> 
> How have you seen dictionaries used? Like following?
> some_dictionary={"predefined_1":"ning","predefined_2":"nang","predefined_3":
> "nong"}


Let's talk a little bit more about why the code above is using a for loop
to construct the dictionary.  Let's look at that fragment again:

###
people_dict = {}
for n in names:
    people_dict[n] = Person(n)
###

What this is saying is "We'll make a variable called 'people_dict' that is
initially assigned to an empty dictionary.  Next, we'll go through each
name in our names list, and add an entry to that dictionary'.


There's a reason why we can't simply initialize people_dict directly:

###
people_dict = { 'marge' : Person('marge'),
                'lisa' : Person('lisa'),
                'bart' : Person('bart'),
                'homer' : Person('homer'),
              }
###

... but we might not know in advance which people we want to create!  



It's true that the source of names can be hardcoded, like this:

###
names = ['marge', 'homer', 'bart', 'lisa']
###



But perhaps we might read it from a flat file,

###

#  We can do something like this in one script:
f = open("simpson_names.txt", "w")
while 1:
    print "Enter the names of simpson family character.  Just press"
    print "the ENTER key to finish."
    name = raw_input()
    f.write(name)
    f.write("\n")
    if name == "\n": break


#  ... and bring the Simpsons to life in another
#  program:
names = map(string.strip, open("simpson_names.txt").read().split())

###



or even from a database!

###
conn = MySQLdb.connect(db='tv_families')
cursor = conn.cursor()
cursor.execute("select name from people where family='simpsons'")
names = map(lambda x: x[0], cursor.fetchall())
###

(I'm just making this example up, but if we did have a tv_families
database, this should work... *grin*)



In any case, we're not anticipating what 'names' looks like, which is why
we do the insertions on an initially empty dictionary.  By doing so, we're
girding ourselves to populate our world with as many Simpsons as we
desire.  Now that's a whimsical thought.  *grin*



If you have questions on this, please feel free to ask.