在python中的字典

OHL*_*ÁLÁ 0 python dictionary

我正在创建服务器 - 客户端通信,我想将一些信息存储在字典中,所以我创建了一个全局字典

global commandList
commandList = {}
Run Code Online (Sandbox Code Playgroud)

当客户端连接到服务器时,我试图以下列方式存储一些信息

self.clientname = str( self.client_address )
commandList[self.clientname]['lastcommand'] = GET_SETUP
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误

commandList[self.clientname]['isready'] = False
KeyError: "('134.106.74.22', 49194)"
Run Code Online (Sandbox Code Playgroud)

更新:

这是代码的一部分.

class MCRequestHandler( SocketServer.BaseRequestHandler ):

    global clientsLock, postbox, rxQueue, disconnect, isRunning, commandList
    postbox = {}    
    rxQueue = Queue.Queue()
    disconnect = {}
    commandList = {}
    clientsLock = threading.RLock()
    isRunning = {}


    def setup( self ):               
        clientsLock.acquire()        
        if len( postbox ) == 0:            
            self.clientname = 'MasterClient'
            postbox['MasterClient'] = Queue.Queue()            
            mess = str( self.client_address );            

            postbox['MasterClient'].put( self.createMessage( MASTER_CLIENT_CONNECTED, mess ) )
            print "Client name: %s" % str( self.clientname )  
            self.request.settimeout( 0.1 )                     
        else:            
            #Send message to the master client            
            self.clientname = str( self.client_address )               
            print "Client name:%s" % self.clientname

            postbox[self.clientname] = Queue.Queue()

            #Setting up the last command
            if not commandList.has_key( self.clientname ):
                commandList[self.clientname] = {}

            commandList[self.clientname]['lastcommand'] = GET_SETUP
            commandList[self.clientname]['isready'] = False            

            self.request.settimeout( COMMANDTABLE[commandList[self.clientname]['lastcommand']]['timeout'] )           

            self.transNr = 0;    
            self.start = True;
            isRunning[self.clientname] = True;

        disconnect[self.clientname] = True                   
        clientsLock.release() 
Run Code Online (Sandbox Code Playgroud)

Ric*_*ard 5

其他人已经指出如何解决这个问题,但也许没有解释为什么.您要做的是在嵌套字典中创建值,或者换句话说,在字典字典中创建值.

因此,您的第一个字典commandList使用键调用self.clientname.这本词典中的每个值实际上都是字典本身 - 或应该是.

你永远不会告诉python这些值应该是字典,但是,你得到一个错误.正如已经指出的那样,从您给出的代码中,这也应该出现在第二个片段中.

有很多方法可以解决这个问题,但最简单的方法是:

if not commandlist.has_key(self.clientname):
    commandlist[self.clientname] = {} # Create an empty dictionary.

commandlist[self.clientname]['secondlevelkey'] = 'value'
Run Code Online (Sandbox Code Playgroud)

您可能有点担心您正在使用全局变量.我看到你这样做是为了线程同步,这是一个坏主意,因为你没有做任何变量锁定或访问控制来防止死/活锁和其他同步错误.如果不知道你如何使用这个命令列表,就不可能说出你应该如何解决它.

如果您提供有关该问题的更多信息,我们可能会建议如何更好地解决它.