[Tutor] Lists on the fly?

Bob Gailer bgailer at alum.rpi.edu
Fri Dec 22 18:46:12 CET 2006


Steve Oldner wrote:
> 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.
>   

counter[w] = 1 # if w is not a key in the dictionary, this assignment adds it, with a value of 1

>   	  


-- 
Bob Gailer
510-978-4454



More information about the Tutor mailing list