Python字典未正确更新

时间:2015-12-02 06:51:23

标签: python dictionary

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

输出:

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]]}}    

即使两个函数调用都使用不同的物理地址列表,两个字典键都有4个物理地址     理想情况下输出应为:

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

1 个答案:

答案 0 :(得分:5)

问题在于声明addressToIdMap = {}。您在模块级别上声明了它,因此在您第二次调用Update_Dictionary函数之前不会将其清除。

您需要将其移至Update_Dictionary

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