[Tutor] Dictionary Issue

Alan Gauld alan.gauld at btinternet.com
Thu Aug 6 01:11:57 CEST 2015


On 05/08/15 15:15, Ltc Hotspot wrote:

> Raw data code reads:

Being picky here but data and code are very different
things (in most languages at least) and what you have
below is definitely code not data.

Meanwhile there are lots of issues in this code...

> fname = raw_input("Enter file name: ")
> handle = open (fname, 'r')
> text = handle.read()
>
> ## The program looks for 'From ' lines and takes the second
> ## word of those lines as the person who sent the mail.
>
> addresses = set()
> for addr in [ text.split()[2]('From  ')
>      if fromline

The above looks like its supposed to be a list
comprehension embedded in a for loop. Putting too much
code in one line is usually a bad idea especially before
you have it working.

Try separating out the formation of your list from the
for loop. Once you get the comprehension working correctly
then you can consider embedding it.

As for the expression

text.split()[2]('From  ')

Can you explain how you think that works?
Try it at the >>> prompt with text set to
a sample line of data.

Try

 >>> text = ...... # whatever your data looks like
 >>> text.split()

 >>> text.split[2]

 >>> text.split()[2]('From  ')

The >>> prompt is one of your most powerful tools while
writing code, you should always have one ready to try
stuff out. You can answer a lot of questions that way.

> ## 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()
>          for wrd in word:

What is word? You don't define it anywhere?

>              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

none is not a value in Python.
You need to spell it None

> for kee, val in count.items():
>      if maxval == none or maxval <val:

You don't really need the maxval == None check since None
is considered less that all other numbers.

>          maxval = val
>          maxkee = kee
>
> print items

What is items? It is not defined anywhere above.
count.items is not the same as items.


-- 
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