在 python 3.5 中将 csv 文件读入 Networkx 图形

reading a csv file into a Networkx graph in python 3.5

我正在按照本教程进行操作:graph tutorial 在我自己的数据文件上。但我陷入了最后一点。代码似乎抛出:

(most recent call last)<ipython-input-193-7227d35394c0> in <module>()
      1 for node in links:  #loops through each link and changes each dictionary to a tuple so networkx can read in the information
      2     edges = node.items()
----> 3     G.add_edge(*edges[0])  #takes the tuple from the list and unpacks the tuples
      4 
      5 nx.draw(G)
TypeError: 'dict_items' object does not support indexing

有解决办法吗?我有点卡住了。

这可能是 python-2 唯一兼容的代码。

在 python 2 中,dict.items() returns 元组列表(键,值),而不是 dict.iteritems()

在python3中,dict.iteritems()已经被移除,dict.items()returns一个迭代器。 所以你必须明确地将它转换为 list 才能通过索引访问元素:

edges = list(node.items())