'dict'对象没有属性'has_key'

Ash*_*shi 72 python dictionary python-3.x

在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
Run Code Online (Sandbox Code Playgroud)

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

为什么我会收到此错误,如何解决?

joh*_*ose 138

has_key已在Python 3中删除.从文档:

  • 删除dict.has_key()- in改为使用运算符.

这是一个例子:

if start not in graph:
    return None
Run Code Online (Sandbox Code Playgroud)

  • @AdamSmith不在Python 3中,`d.keys()`是一个实现大多数set接口的视图. (3认同)
  • 它删除了...但为什么呢?因为它使 python 2 端口到 python 3 有更多的工作要做。 (3认同)
  • 我认为 `key not in d.keys()` 可能也会慢很多,因为 `key not in d` 应该是 O(1) 查找,并且我相信 `keys` 会生成一个列表,即 O(n )查找(更不用说占用额外的内存空间)。不过我可能是错的——它可能仍然是散列查找 (2认同)

小智 40

在python3中,has_key(key)被替换为__contains__(key)

在python3.7中测试:

a = {'a':1, 'b':2, 'c':3}
print(a.__contains__('a'))
Run Code Online (Sandbox Code Playgroud)

  • 不,不,不...`__contains__()` 方法是您在用户定义的类中*实现*包含测试的方式,`in` 运算符是您实际*使用*该测试的方式。大约唯一一次您应该显式调用双下划线的“魔术”方法是在子类方法中,作为调用超类实现的一部分。 (6认同)

Abh*_*tra 12

has_keyPython 3.0中已被弃用。或者,您可以使用“ in”

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

print('A' in graph)
>> True

print('E' in graph)
>> False
Run Code Online (Sandbox Code Playgroud)


Mo-*_*ang 6

尝试:

if start not in graph:
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅ProgrammerSought


Kev*_*n S 5

我认为,仅in在确定键是否已存在时才使用它,它被认为是“更多的pythonic” ,例如

if start not in graph:
    return None
Run Code Online (Sandbox Code Playgroud)