[Tutor] Dictionary Issue
Alan Gauld
alan.gauld at btinternet.com
Thu Aug 6 03:21:25 CEST 2015
On 05/08/15 23:58, Ltc Hotspot wrote:
> fname = raw_input("Enter file name: ")
> handle = open (fname, 'r')
> for line in handle:
> if line.startswith("From: "):
> address = line.split()[1]
>
So far so good.
>
> ## The program creates a Python dictionary that maps
> ## the sender's mail address to a count of the number
> ## of times they appear in the file.
>
> count = dict()
But here you create a brand new dictionary.
Every time you go round the loop.
And it wipes out the old one.
You need to move that out of the loop.
> for wrd in address:
address is a string. So wrd will be set to every
character in the string. I don;t think that's what
you want?
> count[wrd]= count.get(wrd,0) +1
>
> ## After the dictionary is produced, the program reads
> ## through the dictionary using a maximum loop to
> ## find the greatest number of mail messages.
>
> maxval = none
> maxkee = none
See my previous email. none should be None.
Case matters in Python.
> for kee, val in count.items():
> if maxval == none or maxval <val:
> maxval = val
> maxkee = kee
>
>
> #items are printed
>
> print address
Notice that address gets reset every time the loop reads
a new line so this will only print the last address.
But maybe that's what you wanted?
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list