Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

dictionary - Python - dict weird dict writing/reading error

I have a problem reading the data from a dictionary I created to save data reconstructed by a function...

The dictionary is written whenever the value of Amp and t is reconstructed, in the loop col. At each row loop, the dictionary is saved in a list.

Part of the code where the dictionary is written:

def OptimalFilter(inNoiseMatrix, inSi, inGsig, inDgSig):
   AmpTime = Verif = dict()
   ListData = []
   for row in range(0,1000):
       for col in range(0,9):
           ...
           ...
           Amp = mm(aCoef.T,Si)
           t   = mm(bCoef.T,Si)/mm(aCoef.T,Si)
           AmpTime.update({'E_Cell_'+str(col+1): Amp, 't_Cell_'+str(col+1): t})
       ListData.append(AmpTime) 
    return ListData

I checked the reconstruction by printing the Amp and t values and they are correct. The problem occurs when I process the list data that the function returns. When I choose a key from the millionaire and iterate in the lists the value is the same:

AmpTimeXTvalid = OptimalFilter(Noise[3000:], XTvalid, gSig[3000:], DgSig[3000:])

for i in range(20):
    print(AmpTimeXTvalid[i]['E_Cell_1'])
9975.71782251447
9975.71782251447
9975.71782251447
9975.71782251447
9975.71782251447
9975.71782251447
9975.71782251447
9975.71782251447
9975.71782251447
9975.71782251447
9975.71782251447
9975.71782251447
9975.71782251447
9975.71782251447

What did I do wrong in writing/reading the dictionary?

question from:https://stackoverflow.com/questions/66056931/python-dict-weird-dict-writing-reading-error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You keep using the same dict object again and again, so in the end all you see is the value of last iteration. You should get a new dict inside the loop and then append it in your ListData. See below.

def OptimalFilter(inNoiseMatrix, inSi, inGsig, inDgSig):
   ListData = []
   for row in range(0,1000):
       for col in range(0,9):
           ...
           ...
           Amp = mm(aCoef.T,Si)
           t   = mm(bCoef.T,Si)/mm(aCoef.T,Si)
           AmpTime = Verif = dict() # GET A DICT EVERYTIME, OTHERWISE ALL YOU DO IS MODIFY THE SAME OBJECT AND APPEND IT ONE MORE TIME.
           AmpTime.update({'E_Cell_'+str(col+1): Amp, 't_Cell_'+str(col+1): t})
       ListData.append(AmpTime) 
    return ListData

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...