TypeError:无法散列的类型:Networkx随机游走代码中以前有效的“ dict”

时间:2019-01-11 00:00:48

标签: python list dictionary key networkx

我以为是可以在networkx节点/边缘图上随机工作。
我最近决定使用导航器更新Anaconda,然后又回来运行我的程序,突然它停止了工作。相反,我现在得到错误代码:

runfile('C:/Users/e17/.spyder-py3/temp.py', wdir='C:/Users/e17/.spyder-py3')
Traceback (most recent call last):

File "<ipython-input-64-51811f4d02fc>", line 1, in <module>
runfile('C:/Users/e17/.spyder-py3/temp.py', wdir='C:/Users/e17/.spyder-py3')

File "C:\Users\e17\Anaconda3\lib\site- 
packages\spyder\utils\site\sitecustomize.py", line 688, in runfile
execfile(filename, namespace)

File "C:\Users\e17\Anaconda3\lib\site- 
packages\spyder\utils\site\sitecustomize.py", line 101, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/e17/.spyder-py3/temp.py", line 19, in <module>
if rc in NodesVisited:

TypeError: unhashable type: 'dict'  

我一直在使用while循环使用随机游走时访问的节点填充字典。字典可以借以进行大量的下游分析,真是太好了。我现在完全不知道如何解决此问题。我认为我需要为字典提供一个密钥,但是我不确定在提供密钥后如何填充字典。无论如何,这是代码:

import networkx as nx
import random


G_fb = nx.karate_club_graph()
counter = 0
loops = 1


mylist = [];
#run while loop for multiple attempts at random walker
while loops <= 1000:

    rc = random.choice(G_fb.nodes())
    NodesVisited = {}

    #Execute random walk
    while counter <= 11:
        if rc in NodesVisited:
                NodesVisited[rc] += 1
        else:
                NodesVisited[rc] = 1

        Neighbors = G_fb.neighbors(rc)
        rc = random.choice(Neighbors)
        counter += 1

    #Organize the node list in most visited with decreasing order
    MostVisited = sorted(NodesVisited, key = NodesVisited.get,reverse = True)

    #Separate the top 10 most visited vertex
    top_top = MostVisited[:10]

    #create a list of most visited sites for plotting for each iteration  
    mylist.append(top_top)


    loops = loops + 1
    counter = 0
print ('all done!')

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

在networkx 1.11中,G.nodes()list。在较新的版本中,它是NodeView对象。此更改是造成您问题的原因。事实证明,从中进行随机选择将返回某个随机节点的数据,这是一个决定。

所以

if rc in NodesVisited

检查rc是否为NodesVisited的密钥。为此,它需要对rc进行哈希处理,但是它不再是节点,而是字典,因此不能。

要解决此问题,请更改

rc = random.choice(G_fb.nodes())

rc = random.choice(list(G_fb.nodes()))

您同样需要更改

Neighbors = G_fb.neighbors(rc)

Neighbors = list(G_fb.neighbors(rc))