Python 从字典中将具有属性的节点添加到图形
所以我有一个字典,我想把键作为节点输入到一个图中。然后,字典中键的值必须成为节点的属性。这是我现在的代码Python 从字典中将具有属性的节点添加到图形,python,python-3.x,dictionary,networkx,Python,Python 3.x,Dictionary,Networkx,所以我有一个字典,我想把键作为节点输入到一个图中。然后,字典中键的值必须成为节点的属性。这是我现在的代码 dictionary = {1:'a', 2:'b', 3:'c', 4:'d'} G.nx.DiGraph() G.add_nodes_from(dictionary.keys(), attribute = dictionary.values()) G.nodes[1] >> {'attribute': dict_values(['a', 'b', 'c', 'd'])} 这
dictionary = {1:'a', 2:'b', 3:'c', 4:'d'}
G.nx.DiGraph()
G.add_nodes_from(dictionary.keys(), attribute = dictionary.values())
G.nodes[1]
>> {'attribute': dict_values(['a', 'b', 'c', 'd'])}
这不是期望的输出。实际上,我只希望键1中的“a”作为属性。期望输出为:
G.nodes[1]
>> {'attribute': 'a'}
所以问题在于分配我的属性。但是我如何才能做到这一点呢?我还没有找到一个直接作为
networkx
函数的答案。但是,下面的代码可以工作
dictionary = {1:'a', 2:'b', 3:'c', 4:'d'}
G=nx.DiGraph()
G.add_nodes_from(dictionary.keys())
for key,n in G.nodes.items():
n["attribute"]=dictionary[key]
然后您可以看到每一个的属性
G.nodes[1]
#result {'attribute': 'a'}
要将属性分配给各个节点,请使用
G.add_edges\u from(X)
,其中X
是(节点,属性dict)
形式的元组列表(或其他容器)。因此,需要为每个节点创建属性字典。让我们用一个列表来理解它
G.add_nodes_from([(node, {'attribute': attr}) for (node, attr) in dictionary.items()])