Search code examples
python-3.xcycleitemspyvis

Nested loops for - the inner loop does not pass through the values


I am writing a loop to add nodes to puvis, I have a dictionary: node-how many times it occurs in the dataset. {noda1:2, noda2:3, noda4:5}. But for some reason, in my cycles, only the first node is added 3 times - as many times as there are keys in the dictionary.

for n in range(len(counter_nodes)):
    for key, value in counter_nodes.items():
        if value < 2:
            net.add_node(n_id = n+1, label=key, value = 10, color = '#DA7B52')
        if 2 < value < 10:
            net.add_node(n_id = n+1, label=key, value = 100, color = '#D75737')
        else: 
            net.add_node(n_id = n+1, label=key, value = 200, color = '#D75737')

perhaps you need to use while?


Solution

  • Yes, I think you need to use a while loop instead of a for loop. The reason is that your for loop is iterating over the keys of the counter_nodes dictionary, but you're adding the same node to the network for each key. This is because the n variable is incremented by 1 for each iteration of the loop.

    To fix this, you can use a while loop to iterate over the counter_nodes dictionary until all of the nodes have been added to the network. You can do this by keeping track of the number of nodes that have been added to the network in a separate variable, and then checking this variable before adding a new node.

    node_count = 0
    while node_count < len(counter_nodes):
        for key, value in counter_nodes.items():
            if value < 2:
                net.add_node(n_id=node_count + 1, label=key, value=10, color='#DA7B52')
            elif 2 < value < 10:
                net.add_node(n_id=node_count + 1, label=key, value=100, color='#D75737')
            else: 
                net.add_node(n_id=node_count + 1, label=key, value=200, color='#D75737')
            node_count += 1