Search code examples
pythonpython-2.6tryton

python for loop and dictionary


in python and tryton I'm confused why I can't get the desired value I wanted; I don't know what's wrong.

Lets say self.pendingapr has a field itemdescription and have 3 indexes, overall it has small, medium, large in itemdescriptions. I really don't know if the problem's is in the for loop:

global M2Mdic
global M2Mldic2
M2Mdic = {}
M2Mldic2 = {}
res = {}

for x in self.pendingapr:
    M2Mdic['itemdescription'] = str(x.itemdescription)
    M2Mldic2[x.id] = M2Mdic

when i print M2Mldic2 it gives me

>>> {1:'large',2:'large',3:'large'}

when I need / and is expecting is

>>> {1:'small',2:'medium',3:'large'}

Solution

  • What is happening is that map variables are references in Python. So in each iteration if the loop you are modifying all M2Mldic2 maps because they are all the same.

    I think your code should be:

    #global M2Mdic
    global M2Mldic2
    M2Mdic = {}
    M2Mldic2 = {}
    res = {}
    
    for x in self.pendingapr:
       M2Mdic = {}
       M2Mdic['itemdescription'] = str(x.itemdescription)
       M2Mldic2[x.id] = M2Mdic