Iterating dictionary items + if statement results in problems

Peter Otten __peter__ at web.de
Mon Apr 15 07:31:03 EDT 2013


Ombongi Moraa Fe wrote:

> hello Team,
> 
> I have this fairly simple script to iterate the dictionary items and check
> if the items match certain values;
> 
> dictionary={'1234567890':001, '0987654321':002}
> for k, v in dictionary.iteritems():
>         .....
>         .....  #suds client statements;
> 
>         if (k == '1234567890' and v == 001):
>                 criteria='Test'
>         elif (k == '0987654321' and v == 002):
>                 criteria='Running'
>         client.service.methodcall(value1,value2,criteria)
> 
> 
> 
> During the first run of the dictionary items, the
> client.service.methodcall is called only once as expected; and a success
> initiation response is received from server. However, during the second
> run, the client.service.methodcall is called twice - when i check the log
> files, i see the client send request is done twice. Duplicate send
> requests of the same parameters results in a error in inititating a
> connection.
> 
> Someone please show me why my second run results in the
> client.service.methodcall() running twice. I can't seem to get a hang on
> it.

methodcall() is inside the for-loop and will be repeated on every iteration.
In your example code the dictionary has two entries -- therefore 
methodcall() will be invoked twice. 

If the length of the dictionary changes from 1 to 2 while your programm is 
running you will see the behaviour you described.

One way to avoid the problem is to omit the loop:

criteria = None
if dictionary.get("1234567890") == 1:
    criteria = "Test"
elif dictionary.get("0987654321") == 2:
    criteria = "Running
else:
    raise Exception("undefined criteria") # for example
client.service.methodcall(value1, value2, criteria)


Note that leading zeros are usually not a good idea as they mark integer 
constants as octal:

>>> 001
1
>>> 010
8
>>> 008
  File "<stdin>", line 1
    008
      ^
SyntaxError: invalid token





More information about the Python-list mailing list