Python中的字典
我正在创建一个服务器和客户端之间的通信,我想把一些信息存储在一个字典里,所以我创建了一个全局字典。
global commandList
commandList = {}
当一个客户端连接到服务器时,我试图用以下方式存储一些信息。
self.clientname = str( self.client_address )
commandList[self.clientname]['lastcommand'] = GET_SETUP
但是我遇到了以下错误。
commandList[self.clientname]['isready'] = False
KeyError: "('134.106.74.22', 49194)"
更新:
这是代码的一部分。
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()
5 个回答
2
我想你需要进行两步初始化。
self.clientname = str( self.client_address )
commandList[self.clientname] = {}
commandList[self.clientname]['lastcommand'] = GET_SETUP
现在试试看。
3
你正在尝试读取一个字典中不存在的值。可以使用 defaultdict
,或者先创建 commandList[self.clientname]
。另外,尽量不要使用全局变量。
import collections
commandList = collections.defaultdict(dict)
5
其他人已经指出了如何解决这个问题,但可能没有解释为什么会这样。
你想做的是创建一个嵌套字典,简单来说,就是一个字典里面还有字典。
所以你的第一个字典叫做 commandList
,它的键是 self.clientname
。这个字典里的每个值实际上也是一个字典——或者说应该是字典。
不过,你并没有告诉 Python 这些值应该是字典,所以你才会遇到错误。正如之前提到的,从你给出的代码来看,这个问题在第二段代码中也应该会出现。
解决这个问题的方法有很多,但最简单的做法是这样:
if not commandlist.has_key(self.clientname):
commandlist[self.clientname] = {} # Create an empty dictionary.
commandlist[self.clientname]['secondlevelkey'] = 'value'
你可能需要稍微担心一下你在使用全局变量。我看到你这样做是为了线程同步,但这其实是个坏主意,因为你没有进行任何变量锁定或访问控制,这样会导致死锁或其他同步错误。如果不知道你是如何使用这个命令列表的,就很难说你该如何解决这个问题。
如果你能提供更多关于问题的信息,我们可能能给出更好的解决建议。