& # 39; dict # 39;对象没有属性'

当在Python中遍历一个图时,我收到这个错误:

'dict'对象没有has_key属性

这是我的代码:

def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if not graph.has_key(start):
return None
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath: return newpath
return None

该代码旨在查找从一个节点到其他节点的路径。代码来源:http://cs.mwsu.edu/~terry/courses/4883/lectures/graphs.html

为什么我得到这个错误,我该如何解决它?

264052 次浏览

has_key在Python 3中被移除。从文档:

  • 删除了dict.has_key() -使用in操作符代替。

这里有一个例子:

if start not in graph:
return None

我认为在确定一个键是否已经存在时,只使用in被认为是“更python化的”

if start not in graph:
return None

文档中的整个代码将是:

graph = {'A': ['B', 'C'],
'B': ['C', 'D'],
'C': ['D'],
'D': ['C'],
'E': ['F'],
'F': ['C']}
def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if start not in graph:
return None
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath: return newpath
return None

写完后,保存文档并按f5

在那之后,你将在Python IDLE shell中运行的代码将是:

find_path(图,' A ', ' D ')

您应该在IDLE中收到的答案是

['A', 'B', 'C', 'D']

has_keyPython 3.0中已弃用。 你也可以使用“在”

graph={'A':['B','C'],
'B':['C','D']}


print('A' in graph)
>> True


print('E' in graph)
>> False

在python3中,has_key(key)__contains__(key)取代

在python3.7中测试:

a = {'a':1, 'b':2, 'c':3}
print(a.__contains__('a'))

试一试:

if start not in graph:

更多信息见ProgrammerSought