用对象作为'id'替换dict(Python)列表中的值

时间:2012-10-02 11:43:57

标签: python dictionary tornado

我需要在WSHandler连接列表中添加更多值(Tornado,Python)。我将连接添加到类似self.connections.append(self)的列表中,但我需要添加更多信息,例如self.connections.append({'id': self, 'keyword' : ''})(稍后会找到当前的self ID并替换关键字。)< / p>

当我尝试根据self对象添加到列表(例如self.connections[self].filter = 'keyword')时,我得到TypeError: list indices must be integers, not WSHandler.

那我怎么能这样做呢?

编辑:管理以找到正确的对象:

def on_message(self, message):
    print message
    for x in self.connections:
        if x['id'] == self:
            print 'found something'
            x['keyword'] = message
            print x['keyword']
            print x

现在,如何从connections删除整个dict?当然,self.connections.remove(self)不再有效。

2 个答案:

答案 0 :(得分:3)

对于此用例,您不需要连接列表。将其存储在对象本身中可能更容易。只需使用self.filter = 'keyword'

否则:

for dict in self.connections:
    if dict['id'] == self:
        dict['keyword'] = 'updated'

或者,如果您赞成简洁而非清晰度:

for dict in [dict for dict in self.connections if dict['id'] == self]:
    dict['keyword'] == 'updated'

要删除,请使用:

for dict in self.connections:
    if dict['id'] == self:
        self.connections.remove(dict)

答案 1 :(得分:1)

由于self.connections是一个列表,因此您只能使用整数对其进行索引(如错误所示)。 self这里是WSHandler对象,不是整数。

我不是龙卷风的专家,所以你应该尝试Hans说的话。

如果你仍然需要按照你提到的方式进行操作,请尝试:self.connections[self.connections.index(self)]在列表中找到自我对象。