[Tutor] dictionary manipulation
Kent Johnson
kent37 at tds.net
Wed Jul 26 19:46:01 CEST 2006
Chris Hallman wrote:
>
> I need some suggestions on how to work with a dictionary. I've got a
> program that builds a dictionary. I need to be able to manipulate the
> different keys and data so that I can write the output to a file AND
> utilize the smtplib to send the data in an email. I had problems using
> the data in the dictionary, so I wrote a crude for loop to strip
> characters:
>
> >>> print result
> {'s0100swa': ['running correct IOS'], 's0300swa': ['INCORRECT running
> IOS'], 's0200swa': ['running correct IOS'], 's0400swa': ['running
> correct IOS']}
>
> results= sorted(result.items ())
>
> >>> print results
> [('s0100swa', ['running correct IOS']), ('s0200swa', ['running correct
> IOS']), ('s0300swa', ['INCORRECT running IOS']), ('s0400swa',
> ['running correct IOS'])]
>
> for x in range(len(results)):
> text = repr(results[x])
> text = text.replace("'", "")
> text = text.replace("(", "")
> text = text.replace(")", "")
> text = text.replace ("[", "")
> text = text.replace("]", "")
> text = text.replace(",", ":")
> output.write(text + "\n")
> output.flush()
> output.write ("\n")
It seems like most of the work you are doing here is getting rid of
characters you don't want that you introduced by using the string
representation of the results list. You will do much better by just
creating the string you want directly. I think you want something like this:
for key, value in sorted(result.items()):
value = value[0] # get the firset item from the value list
line = '%s: %s\n' % (key, value)
output.write(line)
Also you are using a list as the value in the dict, but all the lists
contain a single string. Maybe you should just store the string directly?
Kent
More information about the Tutor
mailing list