Harish Basavaraju
Harish Basavaraju

Reputation: 67

Python Dictionary not getting updated correctly

mydict = {}        
bufferID = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]    
physicalAddrList1 = [9,8]    
physicalAddrList2 = [10,11]    
addressToIdMap = {}
def Update_Dictionary(physicalAddrList,cmdId,opcode): 
    for address in physicalAddrList:
         list = GetBufferId()
         addressToIdMap[address] = list 
         mydict[cmdId,opcode] = addressToIdMap
def GetBufferId():
    list = []
    list.append([bufferID.pop(),25])
    return list 

Update_Dictionary(physicalAddrList1,1,0x01)    
Update_Dictionary(physicalAddrList2,2,0x02)      
print mydict

OutPut:

C:\Users\29213\Desktop> list4.py
{(1, 1): {8: [[25, 25]], 9: [[26, 25]], 10: [[24, 25]], 11: [[23, 25]]}, (2, 2): {8: [[25, 25]], 9: [[26, 25]], 10: [[24, 25]], 11: [[23, 25]]}}    

Even though both function calls are made with different physical address list, both dictionary keys have all 4 physical address .
Ideally output should be:

{(1, 1): {8: [[25, 25]], 9: [[26, 25]]}, (2, 2):{10: [[24, 25]], 11: [[23, 25]]}}

Upvotes: 1

Views: 59

Answers (1)

Szymon
Szymon

Reputation: 43023

The problem is with the declaration addressToIdMap = {}. You declared it on the module level, so it's not cleared before you call your Update_Dictionary function the second time.

You need to move it inside Update_Dictionary

def Update_Dictionary(physicalAddrList,cmdId,opcode): 
    addressToIdMap = {}
    for address in physicalAddrList:
         list = GetBufferId()
         addressToIdMap[address] = list 
         mydict[cmdId,opcode] = addressToIdMap

Upvotes: 5

Related Questions