Jan Novák Jan Novák - 2 years ago 75
Python Question

Assigning function to a dictionary key - Python

I have a problem, where I'm assigning function to an "entry" in dictionary.
This is from the code:

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

And this is the traceback. From what I understand, it thinks I'm trying to call a string.

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__
File "C:\Users\Radek Golan\Desktop\Sequencer\Sequencer_Server.py", line 58, in handle
TypeError: 'str' object is not callable

And this is the dictionary being listed out:

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

What am I doing wrong?

Answer Source

Your iteration here:

for request in assignment:

Is giving you the keys of your dictionary. Not the values. To get the values when iterating the way you are, you want:

for request in assignment:


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

Even more simple just use values instead:

for value in assignment.values():

Take a look at the dictionary documentation to get more acquainted with it:


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download