python - 当方法返回时字典缺少键

标签 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)

问题是我的日志文件显示字典已创建并且在 package_path_list 方法中存在良好,并且 bfs_pathfinder 方法的日志正确显示了该值,但 key 显示为 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]}

我在这里没有看到任何错误的引用分配。有人可以指出错误吗?我有什么遗漏的吗?

最佳答案

问题出在这里:

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

当您追加到列表时,它会就地发生,并且返回 None不是列表。您需要执行以下两个步骤:

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

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

关于python - 当方法返回时字典缺少键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21399903/

相关文章:

python - 如何找到 Pandas 数据框中最大值的行和列的索引?

python - Pybind11:带有 lambda 的 init<>

python-3.x - `form.validate_on_submit()` 和 `form.validate()` 的区别

Python从配置创建字典的字典

java - 按值对 Map<Key, Value> 进行排序

javascript - python 3 : How to extract url image?

python - Django 3.0 : Running backgound infinite loop in app ready()

python-3.x - 将 df 中的所有列与 Pandas 结合(itertools)

python-3.x - 在 Python 中使用 FFMPEG 时导致此错误的原因是什么?

python - 将文件中的元素与嵌套字典python匹配