Search code examples
pythonalgorithmdictionarynetworkxdefaultdict

Put an element in the right position in defaultdict


Hi im new to python and im trying to create my first program to find clusters of nodes which have +1 sign. I have a file with 3 columns(starting node, ending node, sign between the nodes) like this:

1   2   1
1   3   1
2   3   1
2   4   -1
2   5   1
3   6   -1
4   7   -1
4   9   -1

I create the graph an i save all the adjacencies in a dictionary. Now i want to save in another dictionary(defaultdict(list)) all the supernodes(team nodes that have +1 sign between them). So i wrote the following code:

G = nx.Graph()
G = nx.read_edgelist('example.txt', delimiter='\t', nodetype=int, data=(('sign', int),))
adjacencies = {}
supernodes = defaultdict(list)

for i in G.nodes:
    adjacencies[i] = list(G.neighbors(i))


flag = 0
if flag == 0:
    for node in G.nodes:
        supernodes[node].append(node)
        flag = 1
        break
else:
    for i in G.nodes():
        for j in adjacencies[i]:
            if G.get_edge_data(i,j) == 1:
                for v in supernodes.values():

i stop the code here because i dont know how to put an element to the right position of dict. The steps that i want to do are: i have supernodes like:

1 : [1,2,3,5]
2 : [4]
3 : [6,8]

etc

1. check if edge(i,j) is +1 and then
2.      if i is in supernodes then add j in the same list where i is
3.      if j is in supernodes then add i in the same list where j is
4.      if i and j is not in supernodes the add a new list in supernodes and add 
        i,j elements

Solution

  • Any particular reason you want to use collections.defaultdict?

    You can use the following code to find your supernodes whether you use a deafaultdict or a regular dict. The method setdefault works in both. Check out what setdefault does here.

    G = nx.read_edgelist('example.txt', delimiter='\t', nodetype=int, data=(('sign', int),))
    
    supernodes = dict()
    for edge in G.edges(data='sign'):
        sign = edge[2]
        if sign == 1:
            node1 = edge[0]
            node2 = edge[1]
            supernodes.setdefault(node1, [node1])
            supernodes.setdefault(node2, [node2])
            supernodes[node1].append(node2)
            supernodes[node2].append(node1)
    

    [edit] Looking at the figure of the graph and understanding what OP wanted, here's a way to do it:

    import networkx as nx
    
    G = nx.read_edgelist('example.txt', delimiter='\t', nodetype=int, data=(('sign', int),))
    G1 = nx.Graph()
    G1.add_weighted_edges_from([edge for edge in G.edges(data='sign') if edge[2]==1])
    G1.add_nodes_from(list(G.nodes))
    supernodes = list(nx.connected_components(G1))
    

    supernodes is a list of sets where each set of nodes is one blob in your picture.