0

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'}
4

3 回答 3

2

You are putting the same object into every value in the M2Mldic2 dictionary. Keep in mind that objects are generally passed by reference, you need to copy them explicitly when you want copies.

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

This creates a separate dictionary for each value in M2Mldic2.

于 2013-04-24T10:23:09.473 回答
1

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
于 2013-04-24T10:22:14.577 回答
1

And why you need intermediate dictionary at all? This is completely redundant

M2mDict={}
for x in self.pendingapr:
    M2Mldic2[x.id] = str(x.itemdescription)

or more Pythonic way(from v.2.7)

M2mDict= = {x.id : str(x.itemdescription) for  x in self.pendingapr}
于 2013-04-24T10:37:42.063 回答