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

时间:2015-11-16 01:19:01

标签: python python-3.x dictionary

在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

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

6 个答案:

答案 0 :(得分:127)

在Python 3中删除了

has_key。来自documentation

  
      
  • 已删除dict.has_key() - 请改用in运算符。
  •   

以下是一个例子:

if start not in graph:
    return None

答案 1 :(得分:6)

has_key Python 3.0 中已被弃用。 或者,您可以使用'in'

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

print('A' in graph)
>> True

print('E' in graph)
>> False

答案 2 :(得分:5)

我认为在确定某个密钥是否已存在时,仅使用in会被视为“更加pythonic”,如

if start not in graph:
    return None

答案 3 :(得分:4)

尝试:

if start not in graph:

有关更多信息,请参见ProgrammerSought

答案 4 :(得分:3)

文件中的整个代码将是:

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

写完后,保存文件并按F 5

之后,您将在Python IDLE shell中运行的代码为:

find_path(graph,'A','D')

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

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

答案 5 :(得分:0)

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

在python3.7中测试过:

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