Find neighboring nodes in graph

I've the following graph:

import networkx as nx
import matplotlib.pyplot as plt

g = nx.Graph()
g.add_edge(131,673,weight=673)
g.add_edge(131,201,weight=201)
g.add_edge(131,303,weight=20)
g.add_edge(673,96,weight=96)
g.add_edge(673,205,weight=44)
g.add_edge(673,110,weight=7)
g.add_edge(201,96,weight=96)
g.add_edge(201,232,weight=10)
nx.draw(g,with_labels=True)
plt.show()
g.nodes(data=True)
g.edges(data=True)

I need to create a function myfunction(g, node_list) that returns a subgraph whose nodes have weight < 50.

For example, if I run myfunction(g, [131, 201]), the output should be:

EdgeDataView([(131, 303, {'weight': 20}), (201, 232, {'weight': 10})])


A way to do that is by looping through all the nodes in your list and finding their neighbors with the nx.neighbors function from networkx. You can then set up an if condition to check the weight of the edge between the node of interest and its neighbors. If the condition satisfies your constraint, you can add the neighbor, the edge, and the weight to your subgraph.

See code below:

import networkx as nx
import matplotlib.pyplot as plt

g = nx.Graph()
g.add_edge(131,673,weight=673)
g.add_edge(131,201,weight=201)
g.add_edge(131,303,weight=20)
g.add_edge(673,96,weight=96)
g.add_edge(673,205,weight=44)
g.add_edge(673,110,weight=7)
g.add_edge(201,96,weight=96)
g.add_edge(201,232,weight=10)

fig=plt.figure(figsize=(10,10))

#Plot full graph
plt.subplot(211)
plt.title('Full graph')
labels_g = nx.get_edge_attributes(g,'weight')
pos_g=nx.circular_layout(g)
nx.draw_networkx_edge_labels(g,pos_g,edge_labels=labels_g)
nx.draw(g,pos=pos_g,with_labels=True)

def check_neighbor_weights(g,nodes):
  subg=nx.Graph() #Create subgraph

  for n in nodes:
    subg.add_node(n)
    neighbors=g.neighbors(n) #Find all neighbors of node n
    for neighs in neighbors:
      if g[n][neighs]['weight']<50: #Check if the weigh t is below 50
        subg.add_edge(n,neighs,weight=g[n][neighs]['weight'])
  return subg

subg=check_neighbor_weights(g,[131,201]) #Returns subgraph of interest

plt.subplot(212)
plt.title('subgraph')
labels_subg = nx.get_edge_attributes(subg,'weight')
pos_subg=nx.circular_layout(subg)
nx.draw_networkx_edge_labels(subg,pos=pos_subg,edge_labels=labels_subg)
nx.draw(subg,pos=pos_subg,with_labels=True)

plt.show()

And the output gives:

enter image description here