[Tutor] Dictionary Issue

Ltc Hotspot ltc.hotspot at gmail.com
Thu Aug 6 20:30:29 CEST 2015


Hi Alan,

I moved counter outside the loop and below dict, maxval = None
maxkee = None are both positioned outside the loop.

URL link to the revisions are available at http://tinyurl.com/nvzdw8k

Question: How do I define Counter

Revised code reads:
fname = raw_input("Enter file name: ")
handle = open (fname, 'r')

counter = dict ()
c = Counter(['address'])

maxval = None
maxkee = None

for line in handle:
    if line.startswith("From: "):
        address = line.split()[1]

for maxkee, val in c.items():

        maxval = val
        maxkee = kee

print maxkee and maxval


Traceback message reads:
NameError
Traceback (most recent call last)
C:\Users\vm\Desktop\apps\docs\Python\assignment_9_4_16.py in <module>()
      3
      4 counter = dict ()
----> 5 c = Counter(['address'])
      6
      7 maxval = None

NameError: name 'Counter' is not defined


Regards,
Hal

On Thu, Aug 6, 2015 at 2:47 AM, Alan Gauld <alan.gauld at btinternet.com>
wrote:

> 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()[1]
> >          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 read.
>
> 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.
>
>
> --
> 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