Search code examples
pythonnetworkxsocial-networking

Issue with using random.choice() with networkx


So, I am getting error with this python script, I am new to python and maybe making a silly mistake, please help me out.

    import networkx as nx
    import matplotlib.pyplot as plt
    import random
    
    G=nx.Graph()
    city_set=['Ranchi','Delhi','Mumbai','Kolkata','Jaipur','Pune','Surat','Chennai']
    
    for each in city_set:
        G.add_node(each)
    
    # nx.draw(G,with_labels=1)
    # plt.show()
    #print(G.nodes())
    
    # name=random.choice(list(G.nodes()))
    # print(name)
    
                                    # Adding edges
        
    costs=[]
    value=100
    
    while(value<2000):
        costs.append(value)
        value+=100
        
    
    while(G.number_of_edges()<16):
        c1=random.choice(G.nodes())
        c2=random.choice(G.nodes())
        
        if (c1!=c2)and (G.has_edge(c1,c2))==0:
            w=random.choice(costs)
            G.add_edge(c1,c2,weight=w)
            
            
    nx.draw(G,with_labels=1)
    plt.show()

The error that I am getting is :-

KeyError                                  Traceback (most recent call last)
<ipython-input-29-67a2861315c5> in <module>
     13 print(G.nodes())
     14 
---> 15 name=random.choice(list(G.nodes()))
     16 print(name)
     17 

D:\ANACONDA\lib\random.py in choice(self, seq)
    260         except ValueError:
    261             raise IndexError('Cannot choose from an empty sequence') from None
--> 262         return seq[i]
    263 
    264     def shuffle(self, x, random=None):

D:\ANACONDA\lib\site-packages\networkx\classes\reportviews.py in __getitem__(self, n)
    275 
    276     def __getitem__(self, n):
--> 277         ddict = self._nodes[n]
    278         data = self._data
    279         if data is False or data is True:

KeyError: 2


Solution

  • G.nodes() returns a NodeView object which is a dictionary type containing data for each node. As stated in the documentation: "If your node data is not needed, it is simpler and equivalent to use the expression for n in G, or list(G)."

    Use casting to a list on G.nodes(): Fixed:

    import networkx as nx
    import matplotlib.pyplot as plt
    import random
    
    G=nx.Graph()
    city_set=['Ranchi','Delhi','Mumbai','Kolkata','Jaipur','Pune','Surat','Chennai']
    
    for each in city_set:
        G.add_node(each)
    
    # nx.draw(G,with_labels=1)
    # plt.show()
    #print(G.nodes())
    
    # name=random.choice(list(G.nodes()))
    # print(name)
    
                                    # Adding edges
    
    costs=[]
    value=100
    
    while(value<2000):
        costs.append(value)
        value+=100
    
    
    while(G.number_of_edges()<16):
        c1=random.choice(list(G.nodes()))
        c2=random.choice(list(G.nodes()))
    
        if (c1!=c2)and (G.has_edge(c1,c2))==0:
            w=random.choice(costs)
            G.add_edge(c1,c2,weight=w)
    
    
    nx.draw(G,with_labels=1)
    plt.show()
    

    Output: enter image description here