[Tutor] dictionary manipulation

Alan Gauld alan.gauld at freenet.co.uk
Wed Jul 26 21:22:17 CEST 2006


Chris, You seem to be going through several hoops that
you don't need here. Let the data structures do the work
of storage and extract the data you want in its various
pieces. You are getting the entire data set in a string
then trying to pick out the bits you want, that defeats
the purpose of having the data structures in the first
place!

>>>> print result
> {'s0100swa': ['running correct IOS'], 's0300swa': ['INCORRECT 
> running IOS'],
> 's0200swa': ['running correct IOS'], 's0400swa': ['running correct 
> IOS']}

So this tells us that result is a dictionary with the keys being 
strings
and the data being a list containing a single string. I'm not sure why
you need the list, if possible lose it and just use the string!

> results= sorted(result.items())

This now replacews the dictionary with a list of tuples.
Each tuple contains the dictiinary key string plus the list
with the string inside - 3 levels of data structure!

> for x in range(len(results)):
>    text = repr(results[x])

It is better to use for loops as Guido intended:

 for res in results:
     text = repr(res)

But in fact this isn't necessary if you iterate over
the original dictionary instead

for key in sorted(result.keys):     a sorted list of keys
      text = key + result[key]   # assuming we can lose the list!

You might want to use string formatting here to tidy it up:

      text = "%s\t%s\n" % (key,result[key]) # add formatting values if 
needed

>    text = text.replace("'", "")
>    text = text.replace("(", "")
>    text = text.replace(")", "")
>    text = text.replace("[", "")
>    text = text.replace("]", "")
>    text = text.replace(",", ":")

and you don;t need any of this gloop

>    output.write(text + "\n")
      output.write(text)  # newline added in the format string

>    output.flush()
> output.write("\n")

Why an extra newline? Just write two newlines above if you really
need the blank lines!

> I need to remove the extra characters so the file and email output 
> isn't
> difficult to read. I also need to be able to use the dictionary data 
> so that
> I can compose the message used by the smtplib.

Hopefully my comments make things clearer

HTH,

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list