Hi guys,

I am reading and doing examples from Python Web Programming and 
Have a question about the dictionary:

counter = {}
file = open("d:\myfile.txt") # the time has come the walrus said
while 1:
    line = file.readline()
    if line == "":
        break
    for w in line.split():
        if counter.has_key(w):
            counter[w] += 1
        else:
            counter[w] = 1
file.close()
words = counter.keys()
words.sort()
wor w in words:
    print w, counter{w}

Output is:

Come 1
Has 1
Said 1
The 2
Time 1
Walaus 1 

????
Okay, I understand counter is set up as a dictionary and a dictionary
has a key and a value.
How does the dictionary get built?  I'm not following the logic in how
the key, the actual word, is having a value assigned.


Thanks,

SteveO 
          




-----Original Message-----
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On
Behalf Of Kent Johnson
Sent: Friday, December 22, 2006 10:38 AM
To: Carlos
Cc: tutor@python.org
Subject: Re: [Tutor] Lists on the fly?

Carlos wrote:
> Hello,
> 
> I am wondering if it is possible to create lists on the fly. The 
> script that I'm working on needs a number of parameters, one of those 
> is population, and this corresponds to the number of solutions that a 
> genetic algorithm generates on each generation (iteration). The thing 
> is that I need to generate one list for each population member and 
> then append the corresponding population members to that particular
list.
> 
> This is only so you can have an idea:
> 
> for i in range(5):
>     'list_%i' % (i) = []
> 
> or:
> 
> for i in range(5):
>     lista_+'%i' % (i) = []
> 
> :-[
> 
> Is this possible?

It is possible, using exec, but it is not the right solution to your
problem. You want a bunch of lists each associated with a name. The way
to do this is put the lists in a dict; the name is the key, the list is
the value. Your example would look like this:

lists = {}
for i in range(5):
   lists['list_%i' % (i)] = []

Kent

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to