当方法返回时,字典缺少键

时间:2014-01-28 07:58:35

标签: python python-3.x dictionary

我有一些代码在我创建的图表上执行修改后的BFS,并在每个节点上存储一些路径信息。 BFS运行完成后,我的代码打包路径列表并返回它。这是控制流程:

Executable->BFS(graph)->Package_Path_List(node)

这是package_path_list方法:

def package_path_list(self, end):
    '''Packages the path list at the destination node
    This method packages the path list for user display and returns the optimal
    paths present at the destination node
    '''
    final_path_list = {}
    dest_id = handler.TOPOLOGY_GRAPH.get_vertex(end.get_id())
    for key, value in end.nodePathTable.items():
        path = list(key)
        # Append the destination’s ID to the end of each path
        final_path_list[(path.append(dest_id))] = value
        pfLogger.debug("Packaging path list: " + str(path) + ":" + str(value))
    return (final_path_list)

hfs_pathfinder方法调用:

testDict = dict(self.package_path_list(end))
pfLogger.debug("Returned Path List: " + str(testDict))
return(testDict)

问题是我的日志文件显示dict是在package_path_list方法中创建并存在的,并且bfs_pathfinder方法的日志正确显示了值,但关键是显示最新为None

以下是日志:

pathfinding:DEBUG:bfspathfinder:345:  Packaging path list: [1 connectedTo: ['2', '4'], 2    
connectedTo: ['1', '3'], 3 connectedTo: ['2', '4']]:[1536.0, 6.0, 18.0]

pathfinding:DEBUG:bfspathfinder:295:  Returned Path List: {None: [1536.0, 6.0, 18.0]}

我在这里看不到任何错误的参考作业。有人可以指出错误吗?有什么我想念的吗?

1 个答案:

答案 0 :(得分:1)

问题在于:

    final_path_list[(path.append(dest_id))] = value

当您append到列表时,它会就地发生,return None列表。您需要执行以下两个步骤:

path.append(dest_id)
final_path_list[tuple(path)] = value

请注意,我将path转换为元组:列表是可变的,因此不能是字典键。