将函数分配给字典键 - Python

时间:2016-04-17 15:18:25

标签: python dictionary

我有一个问题,我将函数分配给字典中的“条目”。 这来自代码:

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 个答案:

答案 0 :(得分: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 :(得分:0)

for循环遍历字典迭代键。您的request变量中会包含"nick1"。您需要assignment[request]("Ping")