Jan Novák Jan Novák - 7 months ago 13
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:
request("PING")
print(request)
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__
self.handle()
File "C:\Users\Radek Golan\Desktop\Sequencer\Sequencer_Server.py", line 58, in handle
request("PING")
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

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:
    print(assignment[request])

or

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():
    print(value)

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

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

Comments