[Tutor] Dictionary Issue
alan.gauld at btinternet.com
Thu Aug 6 11:47:56 CEST 2015
On 06/08/15 03:27, Ltc Hotspot wrote:
> The output as reported by the latest code revision: cwen at iupui.edu
> <mailto:cwen at iupui.edu> 1← Mismatch
> Looks like python continues to print the wrong data set:
Python will print what you ask it to. Don't blame the tool! :-)
> for line in handle:
> if line.startswith("From: "):
> address = line.split()
> count[address]= count.get(address,0) +1
> maxval = None
> maxkee = None
> for kee, val in count.items():
> maxval = val
> maxkee = kee
> print address, val
Look at the loops.
In the second loop you are no longer setting the values to
those of the max item but are setting them every time.
So at the end of the loop val holds the val of
the last item (and so does maxval so even if you used
that it would be the same result).
Similarly with the code for address. You are setting that
for each 'From ' line in your file so at the end of the loop
address is the last address in the file.
Now, dictionaries do not store data in the order that you
insert it, so there is no guarantee that the last item in
the dictionary loop is the same as the last address
You need to reinstate the test for max val in the second
loop and then print the kee that corresponds with that
(maxkee) as the address. ie. print maxkee and maxval.
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:
More information about the Tutor