Problem with a dictionary program....

Ling Lee janimal at mail.trillegaarden.dk
Tue Sep 28 17:04:28 CEST 2004


So this code should work:

indput = raw_input(" Tell me the number you want to transform to textuel 
representaion")
try:
    indput = str(int(indput))
except ValueError:
    print "No, you need to give me an integer."

List = 
{1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine"}
output = []
for character in indput:
  output.append(List[character])
  print ', '.join(output)

I read it like this first output is an empty list, then for each character 
in the input it will be run through the "List" and when it find the number 
it will apend it to the output, and in the last print line it will join the 
output ( if there has been more than one number) and print it-

But if I run the program and type in the number 34 I get the error:

Traceback (most recent call last):
  File "C:/Python23/taltilnumre.py", line 10, in -toplevel-
    output.append(List[character])
KeyError: '3'

How can that be, it looks right to me ...

Thanks


"Jeffrey Froman" <jeffrey at fro.man> wrote in message 
news:10liubfprlt4g9d at corp.supernews.com...
> Ling Lee wrote:
>
>> After I have gotten the lenght of the string, I will write a loop, that
>> goes through the dictionary as many times as the lengt of the string, and
>> the gives me the corresponding numbers, the numner 21 would go 2 times
>> through the loop and give me the output two one.
>
> There is no need to count the length. You can iterate over each character 
> in
> a Python string (or other object) without first calculating the size of 
> the
> loop, like so:
>
> output = []
> for character in indput:
> output.append(List[character])
> print ', '.join(output)
>
> As Russel pointed out, you'll have to iterate over indput as as a 
> string --
> not convert it to an integer first, because you can't iterate over an
> integer's digits, but you can iterate over a string's characters.
>
> Jeffrey 





More information about the Python-list mailing list