Python 使用networkX向节点添加属性

Python 使用networkX向节点添加属性,python,igraph,networkx,Python,Igraph,Networkx,我使用igraph计算了每个节点的最佳网络数,下面是我使用的代码 import igraph g = igraph.Graph.Read_Ncol('data.txt') dendrogram = g.community_edge_betweenness() clusters = dendrogram.as_clustering() membership = clusters.membership 现在我想使用networkX中的set\u node\u attributes函数来标记每个节点

我使用igraph计算了每个节点的最佳网络数,下面是我使用的代码

import igraph
g = igraph.Graph.Read_Ncol('data.txt')
dendrogram = g.community_edge_betweenness()
clusters = dendrogram.as_clustering()
membership = clusters.membership
现在我想使用networkX中的
set\u node\u attributes
函数来标记每个节点的社区数量。因此,如果我运行
nx.get\u node\u attributes(g,'counts')
它应该生成

{123: 2,
 124: 3,
 125: 4 and so on} where "123" is a node and "2" is the count associated 
我想在这里使用for循环,但不确定如何开始

编辑:

membership
#output: 
[2,
 3,
 4]

我假设
membership
是一个字典,节点作为键,计数作为值,然后根据您使用的networkx版本(我使用的是v2.1),检查
set\u node\u attributes
,对于1,它是
set\u node\u attributes(G,value,name=None)
, 所以你就这么做了

nx.set_node_attributes(G, membership, 'counts')

print G[123]['count']
#output 2
然后使用
get\u node\u attributes
提取相同的字典

更新:假设
成员资格
是一个计数列表,那么它的顺序将与
G.nodes()
相同,因此我们可以

node_list = list(G.nodes())

count_dict = { k:v for k,v in zip(node_list,membership)}
那就做吧

nx.set_node_attributes(G, count_dict, 'counts')

我猜“会员资格”在这里不是字典。我应该写一个for循环来创建一个以节点为键,以计数为值的循环吗?
nx.set_node_attributes(G, count_dict, 'counts')