How to check if an edge has an attribute in Networkx

爷,独闯天下 提交于 2019-12-10 14:11:54

问题


I created a graph in yEd and I want to check if an edge has an attribute. For example some edges have a label but some dont. When I try to do this I get an an error:

for n, nbrs in G.adjacency_iter():
  for nbr,eattr in nbrs.items():
    evpn = eattr['vpn']
    elabel = eattr['label']  #error is here
    if evpn != "No":
      nlabel = G[n].get("label")
      platform = G[n].get("platform")
      if G[nbr].get("platform") == platform:
        g_vpn.add_nodes_from([n,nbr], label, platform) # I dont know if this way 
                                                 #to set attributes is right

While vpn attribute works because I have set a default value. I know I could just put a label value in all edges but I want my program to check if label is missing and setting a default value like what I do below. Although it doesn't work because it can't find the label attribute in some edges:

for e,v in G.edges():
  if G[e][v].get("label") == ""
  label = "".join("vedge",i)
  i+=1
  G[e][v]['label']=label

Also if you could check the rest of that code and tell me if it needs any improvement or make some things easier to do. Thanks


回答1:


The edge attributes are stored as a dictionary so you can test to see if the key is in the dictionary:

In [1]: import networkx as nx

In [2]: G = nx.Graph()

In [3]: G.add_edge(1,2,color='blue')

In [4]: G.add_edge(2,3)

In [5]: 'color' in G[1][2]
Out[5]: True

In [6]: 'color' in G[2][3]
Out[6]: False


来源:https://stackoverflow.com/questions/17255354/how-to-check-if-an-edge-has-an-attribute-in-networkx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!