2016-04-17 333 views
0

我有一個問題,我在哪裏將函數賦值給字典中的「條目」。 這是從代碼:爲字典鍵分配函數 - Python

assignment[message[0]] = self.request.sendall 
if members == 0: 
    for request in assignment: 
     request("PING") 
     print(request) 
     print("Sent PING") 

而這是追溯。根據我的理解,它認爲我正在嘗試調用一個字符串。

Traceback (most recent call last): 
File "C:\Python27\lib\SocketServer.py", line 295, in_handle_request_noblock 
self.process_request(request, client_address) 
File "C:\Python27\lib\SocketServer.py", line 321, in process_request 
self.finish_request(request, client_address) 
File "C:\Python27\lib\SocketServer.py", line 334, in finish_request 
self.RequestHandlerClass(request, client_address, self) 
File "C:\Python27\lib\SocketServer.py", line 655, in __init__ 
self.handle() 
File "C:\Users\Radek Golan\Desktop\Sequencer\Sequencer_Server.py", line 58, in handle 
request("PING") 
TypeError: 'str' object is not callable 

,這是字典被列了出來:

{'nick1': <bound method _socketobject.sendall of <socket._socketobject object at 0x02883EA0>>, 'nick2': <bound method _socketobject.sendall of <socket._socketobject object at 0x02883FB8>>} 

我在做什麼錯?

回答

2

您的迭代的位置:

for request in assignment: 

是給你的鑰匙你的字典中。不是價值。要迭代你的方式時,你得到的值,你想:

for request in assignment: 
    print(assignment[request]) 

for key, value in assignment.items(): 
    print("key {}".format(key)) 
    print("value {}".format(value)) 

更簡單隻需使用values代替:

for value in assignment.values(): 
    print(value) 

看看字典以獲得更多的知識:

https://docs.python.org/3/tutorial/datastructures.html#dictionaries

+1

或'爲了assignent.values()的價值'。 – GingerPlusPlus

+0

@GingerPlusPlus呃..當然!謝謝 – idjaw

+1

或在Python 2中爲'assign.itervalues()'中的值。 – letmutx

0

for循環字典遍歷鍵。你的request變量將有"nick1"在裏面。你需要assignment[request]("Ping")