networkx节点属性如果不存在,请创建它



我需要检查一个节点是否有属性(对于一个节点来说,该属性根本不可能存在(。类似这样的东西会返回一个"KeyError:'size"。

G = nx.Graph()
G.add_node("firstNode")
for node in G.nodes:
if(G.nodes[node]['size'] is None):
G.nodes[node]['size']=35    
#KeyError: 'size'

如果我们检查什么类型的对象是G.nodes[node],我们可以看到这是一个字典。

type(G.nodes[node])
# result <class 'dict'>

当您试图访问字典中不存在的密钥时,会出现此错误。看看这个问题我';我在python中得到Key错误。

你有两种方法来处理这个问题:

import networkx as nx
G = nx.Graph()
G.add_node("firstNode")
# option 1
for node in G.nodes:
node_dict = G.nodes[node]
if node_dict.get('size') is None:
node_dict['size']=35
# option 2
for node in G.nodes:
node_dict = G.nodes[node]
if 'size' not in node_dict or node_dict['size'] is None:
node_dict['size']=35

最新更新