How can I correct the error ' AttributeError: 'dict_keys' object has no attribute 'remove' '?

前端 未结 1 992
误落风尘
误落风尘 2020-12-09 10:59

I was trying shortest path finder using dijkstra algorithm but It seems not working. Can\'t figure out what the problem is. Here are the code and the error message. (I\'m w

1条回答
  •  余生分开走
    2020-12-09 11:03

    In Python 3, dict.keys() returns a dict_keys object (a view of the dictionary) which does not have remove method; unlike Python 2, where dict.keys() returns a list object.

    >>> graph = {'a': []}
    >>> keys = graph.keys()
    >>> keys
    dict_keys(['a'])
    >>> keys.remove('a')
    Traceback (most recent call last):
      File "", line 1, in 
    AttributeError: 'dict_keys' object has no attribute 'remove'
    

    You can use list(..) to get a keys list:

    >>> keys = list(graph)
    >>> keys
    ['a']
    >>> keys.remove('a')
    >>> keys
    []
    

    unseen_nodes = graph.keys()
    

    to

    unseen_nodes = list(graph)
    

    0 讨论(0)
提交回复
热议问题