Python 方法返回时字典缺少键
我有一些代码在我创建的图上执行修改后的BFS,并在每个节点上存储一些路径信息。BFS运行完成后,我的代码打包路径列表并返回它。以下是控制流程:Python 方法返回时字典缺少键,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我有一些代码在我创建的图上执行修改后的BFS,并在每个节点上存储一些路径信息。BFS运行完成后,我的代码打包路径列表并返回它。以下是控制流程: Executable->BFS(graph)->Package_Path_List(node) 这是package\u path\u list方法: def package_path_list(self, end): '''Packages the path list at the destination node This
Executable->BFS(graph)->Package_Path_List(node)
这是package\u path\u 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)
testDict = dict(self.package_path_list(end))
pfLogger.debug("Returned Path List: " + str(testDict))
return(testDict)
由hfs_pathfinder的方法调用:
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)
testDict = dict(self.package_path_list(end))
pfLogger.debug("Returned Path List: " + str(testDict))
return(testDict)
问题是,我的日志文件显示dict是在package\u path\u list
方法中创建并存在的,而bfs\u 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]}
我在这里没有看到任何错误的参考作业。有人能指出错误吗?我有什么遗漏吗?问题在于:
final_path_list[(path.append(dest_id))] = value
当您将
附加到列表中时,它会在适当的位置发生,并将返回None
,而不是列表。您需要执行以下两个步骤:
path.append(dest_id)
final_path_list[tuple(path)] = value
请注意,我将path
转换为一个元组:列表是可变的,所以不能是字典键 非常感谢。我不知道列表的就地行为。我为此绞尽脑汁了整整一个小时。感谢您的帮助。:)