Python字典未正确更新

Har*_*aju 1 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
Run Code Online (Sandbox Code Playgroud)

输出:

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]]}}    
Run Code Online (Sandbox Code Playgroud)

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

{(1, 1): {8: [[25, 25]], 9: [[26, 25]]}, (2, 2):{10: [[24, 25]], 11: [[23, 25]]}}
Run Code Online (Sandbox Code Playgroud)

Szy*_*mon 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
Run Code Online (Sandbox Code Playgroud)